电话有效时保持服务

时间:2014-01-27 16:18:33

标签: android

我有广播接收器,可以在手机启动时激活

public class autostart extends BroadcastReceiver {
    public void onReceive(Context arg0, Intent arg1) {
        Intent intent = new Intent(arg0, MyService.class);
        arg0.startService(intent);
        Log.i("Autostart", "started");
    }
}

该服务非常简单,它只是注册了一个广播接收器,只能通过代码注册,而不能从清单注册

public class MyService extends Service
{
    private static final String TAG = "MyService";
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
    }

    ScreenOffReceiver actionScreenOffReceiver;
    @Override
    public void onStart(Intent intent, int startid)
    {

        try {
            IntentFilter intentfilter = new IntentFilter();
            intentfilter.addAction(Intent.MY_ACTION);
            registerReceiver(actionScreenOffReceiver = new ScreenOffReceiver(),
                    intentfilter);
        } catch (Exception e) {
        }
    }
}

问题在于,如果应用程序关闭,例如在某些活动上调用finish(),那么服务就会死掉。

如何在手机开机前保持服务正常运行

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您只需在BroadcastReceiver

中添加此代码即可Service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

来源:Service | Android Developers