如何在重新启动后通过服务启动活动
问题描述:
我需要我的应用程序在重新启动设备后开始运行(在后台)。下面是我想出现在为止(后服用大量从这里帮助...)如何在重新启动后通过服务启动活动
这是我BootUpReceiver利用广播接收器的:
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, RebootService.class);
serviceIntent.putExtra("caller", "RebootReceiver");
context.startService(serviceIntent);
}
}
这是服务类:
public class RebootService extends IntentService{
public RebootService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
protected void onHandleIntent(Intent intent) {
Intent i = new Intent(getBaseContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String intentType = intent.getExtras().getString("caller");
if(intentType == null)
return;
if(intentType.equals("RebootReceiver"))
getApplication().startActivity(i);
}
}
这是我的Android清单:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".BootUpReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name=".RebootService"/>
</application>
的问题是,当我安装这在我的手机上,并重新启动,该应用程序崩溃:它说,“传输已停止工作”。按OK按钮后,当我检查应用程序信息时,该应用程序正在运行。
我是新来的android,我不知道发生了什么。我应该添加更多的权限?
请帮忙。 TIA
答
我认为你的问题在于你的RebootService构造函数。当系统调用它时,它不提供任何参数,所以它会崩溃。如果您在日志中查找你可能会看到的东西的影响“无法实例化服务......”
试着用替换你的构造:
public RebootService() {
super("Reboot Service");
}
感谢。让我试试看,并找回你..我找到了构造函数腥 – blueren
更新:它的作品。现在,当我重新启动时,活动启动..但我真正想要的是应用程序在后台启动:| – blueren
这是您的设计问题,而不是代码问题。你正在开始一个活动,这将在前台出现。如果你想在后台使用它,那么你必须在你的服务中做任何你正在做的事情,而不是开始一个活动。 – Ralgha