我是android开发的新手。我的服务在启动循环之前被杀了 我从MainActivity等其他活动开始服务
package com.example.ch_m_usman.sharedtasklist.Services;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class ReminderService extends IntentService {
public ReminderService() {
super("Reminder Service");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.e("check","")
//Loop does not start.
for (int i=0;i<5;i++){
Log.e("Inside for","");
}
}
}
//How to use loop in intent service
答案 0 :(得分:0)
使用以下代码:
public class TaskConfirm extends IntentService {
private final IBinder mBinder = new LocalBinder();
public TaskConfirm() {
super("TaskConfirm");
setIntentRedelivery(true);
}
@Override
public void onCreate() {
super.onCreate();
//Initilise your objects here like below...
taskIdList=new ArrayList<String>();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
// get intent data here like below if required......
if (intent != null) {
String taskId=intent.getStringExtra("taskId");
}
// apply your loop here .......
for (int i=0;i<5;i++){
Log.e("Inside for","");}
}
public class LocalBinder extends Binder {
public TaskConfirm getService() {
return TaskConfirm.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
从您的活动开始如下服务:
Intent serviceIntent = new Intent(context, TaskConfirm.class);
// put some extra data if required
serviceIntent.putExtra("taskId","1");
startService(serviceIntent);
如果要在其他活动中访问此服务,请将该活动绑定到服务:
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, TaskConfirm.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
TaskConfirm.LocalBinder binder = (TaskConfirm.LocalBinder) service;
mService = binder.getService();
mBound = true;
// do your task on service-connected...
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};