我试过了:
这在我的手机上不起作用: Trying to start a service on boot on Android
这也无法正常工作: http://www.compiletimeerror.com/2014/12/android-autostart-app-after-boot-with.html#.VpL6sxWLTIU
还有一些我再也找不到的。有人可以发布一个代码的工作示例,它将使用默认的HelloWorld xml布局启动MainActivity吗?
代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity
android:name=".MyService"
android:label="@string/title_activity_my_service" >
</activity>
</application>
</manifest>
package com.example;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
context.startService(startServiceIntent);
}
}
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MyService extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_service);
}
}
答案 0 :(得分:0)
首先:创建一个BroadcastReceiver,onReceive(Context context,Intent intent),启动你要在这个方法中启动的app
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
xxx.class is the app you want to start
Intent service = new Intent(context,XXXclass);
context.startService(service);
Log.v("TAG", "you want to startup this app.....");
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
context.startActivity(intent);
} }
其次:配置接收器和intent-filter
<receiver android:name="BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
三,添加权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />