Если во время проверки не появляется ошибка MySQL, убедитесь, что вы правильно создали таблицу базы данных. Это случилось со мной. Ищите любые нежелательные запятые или цитаты.
Первый контекст (может быть Activity / Service и т. д.)
У вас есть несколько вариантов:
1) Используйте Bundle из Intent :
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) Создайте новый Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
3) Используйте метод ярлыка putExtra () для Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
Новый контекст (может быть Activity / Service и т. Д.)
Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(key);
}
ПРИМЕЧАНИЕ: Связки имеют методы «get» и «put» для всех примитивных типов, Parcelables и Serializables. Я просто использовал Strings для демонстрационных целей.
Для точного ответа на этот вопрос на тему «Как отправить данные с помощью намерения из Activity to Service», вам нужно переопределить метод onStartCommand()
, в котором вы получаете объект намерения:
Когда вы создаете Service
, вы должны переопределить метод onStartCommand()
, поэтому, если вы внимательно посмотрите на подпись ниже, вы получите объект intent
, который передается ему:
public int onStartCommand(Intent intent, int flags, int startId)
Итак, из активности вы создадите объект-объект для запуска службы, а затем разместите свои данные внутри объекта-объекта, например, вы хотите передать UserID
с Activity
на Service
:
Intent serviceIntent = new Intent(YourService.class.getName())
serviceIntent.putExtra("UserID", "123456");
context.startService(serviceIntent);
Когда служба запускается, метод onStartCommand()
будет вызван так в этом методе, вы можете получить значение (UserID) из объекта-объекта, например,
public int onStartCommand (Intent intent, int flags, int startId) {
String userID = intent.getStringExtra("UserID");
return START_STICKY;
}
Примечание: выше answer указывает, чтобы получить Intent с getIntent()
методом, который неверен в контексте службы
Другая возможность - use.getAction:
In Service:
public class SampleService inherits Service{
static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START";
static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1";
static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2";
static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
//System.out.println("ACTION: "+action);
switch (action){
case ACTION_START:
startingService(intent.getIntExtra("valueStart",0));
break;
case ACTION_DO_SOMETHING_1:
int value1,value2;
value1=intent.getIntExtra("value1",0);
value2=intent.getIntExtra("value2",0);
doSomething1(value1,value2);
break;
case ACTION_DO_SOMETHING_2:
value1=intent.getIntExtra("value1",0);
value2=intent.getIntExtra("value2",0);
doSomething2(value1,value2);
break;
case ACTION_STOP_SERVICE:
stopService();
break;
}
return START_STICKY;
}
public void startingService(int value){
//calling when start
}
public void doSomething1(int value1, int value2){
//...
}
public void doSomething2(int value1, int value2){
//...
}
public void stopService(){
//...destroy/release objects
stopself();
}
}
В действии:
public void startService(int value){
Intent myIntent = new Intent(SampleService.ACTION_START);
myIntent.putExtra("valueStart",value);
startService(myIntent);
}
public void serviceDoSomething1(int value1, int value2){
Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1);
myIntent.putExtra("value1",value1);
myIntent.putExtra("value2",value2);
startService(myIntent);
}
public void serviceDoSomething2(int value1, int value2){
Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2);
myIntent.putExtra("value1",value1);
myIntent.putExtra("value2",value2);
startService(myIntent);
}
public void endService(){
Intent myIntent = new Intent(SampleService.STOP_SERVICE);
startService(myIntent);
}
Наконец, в файле манифеста:
<service android:name=".SampleService">
<intent-filter>
<action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/>
<action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/>
<action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/>
<action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/>
</intent-filter>
</service>
Активность:
int number = 5;
Intent i = new Intent(this, MyService.class);
i.putExtra("MyNumber", number);
startService(i);
Услуга:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getExtras() != null){
int number = intent.getIntExtra("MyNumber", 0);
}
}
Если вы связываете свою службу, вы получите Экстра в onBind(Intent intent)
.
Активность:
Intent intent = new Intent(this, LocationService.class);
intent.putExtra("tour_name", mTourName);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
Услуга:
@Override
public IBinder onBind(Intent intent) {
mTourName = intent.getStringExtra("tour_name");
return mBinder;
}
Сервис: startervice может вызвать побочные эффекты, лучший способ использовать мессенджер и передавать данные.
private CallBackHandler mServiceHandler= new CallBackHandler(this);
private Messenger mServiceMessenger=null;
//flag with which the activity sends the data to service
private static final int DO_SOMETHING=1;
private static class CallBackHandler extends android.os.Handler {
private final WeakReference<Service> mService;
public CallBackHandler(Service service) {
mService= new WeakReference<Service>(service);
}
public void handleMessage(Message msg) {
//Log.d("CallBackHandler","Msg::"+msg);
if(DO_SOMETHING==msg.arg1)
mSoftKeyService.get().dosomthing()
}
}
Упражнение: Get Messenger from Intent залейте его данными и передайте сообщение обратно в службу
private Messenger mServiceMessenger;
@Override
protected void onCreate(Bundle savedInstanceState) {
mServiceMessenger = (Messenger)extras.getParcelable("myHandler");
}
private void sendDatatoService(String data){
Intent serviceIntent= new
Intent(BaseActivity.this,Service.class);
Message msg = Message.obtain();
msg.obj =data;
msg.arg1=Service.DO_SOMETHING;
mServiceMessenger.send(msg);
}