在Android系统中,有界面的app一定是有Activity的,没有界面的app,那就是一个Service了。
Service如何启动呢?办法和Activity的启动一样,也是Intent对象。我讲的是如何写一个开机后台启动的app。
首先是AndroidMainfest注册开机启动权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <!-- 开机自启动所需用的权限 -->
还要注册广播消息接受者:<receiver android:name=".BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
接下来是广播接收者:
public class BootReceiver extends BroadcastReceiver {
private String LOG = "BootReceiver";
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.i(LOG, "onReceive");
Intent mBootIntent = new Intent(arg0, MyService.class);
arg0.startService(mBootIntent);
}
}
MyService.Java:
public class APTService extends Service {
private String LOG = "APTService";
public void onCreate() {
super.onCreate();
Log.i(LOG, "Oncreate");
Toast.makeText(getApplicationContext(), LOG + "onCreate start!",
Toast.LENGTH_LONG).show();
run(context);
Toast.makeText(getApplicationContext(), LOG + "onCreate end!",
Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i(LOG, "onBind");
Toast.makeText(getApplicationContext(), LOG, Toast.LENGTH_LONG).show();
return null;
}
}
这样做,你开机的时候就能收到Toast消息了!
个人辛勤劳动成果,如有转载,请注明出处,谢谢!