问题描述
我已经制作了使用一个后台服务的Android应用程序。它运行良好,但如果用户重启他的设备,我的应用程序将停止。如何修复它,即如何在重启设备后重新启动应用程序?
I have made Android application which uses one background service. It works good, but if user reboot his device that my application will be stopped. How can I fix it, i.e. how can I restart my application after rebooting of device?
推荐答案
您可以通过以下方式执行此操作:
You can do this in following way :
注册一个将在boot_completed时启动的接收器,并在android中添加以下权限:
Register a receiver which will be initiated when boot_completed and add the following permission in android :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
并在清单文件中添加以下行:
and add following lines in manifest file:
<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>
现在在MyDeceiver的 onReceive()方法启动服务:
Now in the onReceive() method of MyReceiver start the service :
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服务方法使用其包名称启动您想要的应用程序:
And now in onCreate method of the service launch the app you want using its package name :
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("package.name");
startActivity( LaunchIntent );
这将满足您的要求。
这篇关于重启设备后如何重启应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!