Android 我需要将值传递给服务类
我需要将值传递给服务类 以下是我从活动中调用服务的方式:Android 我需要将值传递给服务类,android,android-service,Android,Android Service,我需要将值传递给服务类 以下是我从活动中调用服务的方式: try { Intent lintent = new Intent(getApplicationContext(), BackgroundService.class); getApplicationContext().stopService(lintent); startService (new Intent(this, BackgroundService.class)); }catch (Exception s){} 这
try {
Intent lintent = new Intent(getApplicationContext(), BackgroundService.class);
getApplicationContext().stopService(lintent);
startService (new Intent(this, BackgroundService.class));
}catch (Exception s){}
这是我的服务:
public class BackgroundService extends Service {
public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;
String obj;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
handler = new Handler();
runnable = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), obj , Toast.LENGTH_LONG).show();
handler.postDelayed(runnable, 10000);
}
};
handler.postDelayed(runnable, 15000);
}
@Override
public void onDestroy() {
/* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
handler.removeCallbacks(runnable);
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
}
我正在努力将价值传递给服务类。任何志愿者都能帮助我吗
Intent serviceIntent = new Intent(this,ListenLocationService.class);
serviceIntent.putExtra("ID", "1234");
startService(serviceIntent);
并在服务类的onStart方法中获取参数
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Bundle extras = intent.getExtras();
if(extras != null) {
String stringID = (String) extras.get("ID");
}
}