我制作了一个使用一个后台服务的Android应用程序。它运行良好,但如果用户重启他的设备,我的应用程序将停止。我该如何解决它,即如何在重启设备后重启我的应用程序?
答案 0 :(得分:6)
您可以通过以下方式执行此操作:
注册将在boot_completed时启动的接收器,并在android中添加以下权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
并在清单文件中添加以下行:
<receiver android:name="com.test.check.MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
<service android:name=".MyService">
<intent-filter>
<action android:name="com.test.check.MyService" />
</intent-filter>
</service>
现在在MyReceiver的 onReceive()方法启动服务:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(arg0, "boot completed",Toast.LENGTH_LONG).show();
Intent serviceIntent = new Intent("com.test.check.MyService");
arg0.startService(serviceIntent);
}
}
现在,onCreate服务方法使用其包名称启动您想要的应用程序:
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("package.name");
startActivity( LaunchIntent );
这将满足您的要求。