Android 之开机启动Service
16lz
2021-01-23
配置文件如下:
定义广播接收器:
定义后台服务类:
定义绑定的Activity
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="net.blogjava.mobile.startupservice" android:versionCode="1"android:versionName="1.0"><application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MessageActivity" android:theme="@android:style/Theme.Dialog"><intent-filter><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><receiver android:name="StartupReceiver"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></receiver><service android:enabled="true" android:name=".MyService" /></application><uses-sdk android:minSdkVersion="3" /><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /></manifest>
定义广播接收器:
public class StartupReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent){Intent serviceIntent = new Intent(context, MyService.class);context.startService(serviceIntent);Intent activityIntent = new Intent(context, MessageActivity.class);//要想在Service中启动Activity ,必须设置如下标志activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(activityIntent);}}
定义后台服务类:
public class MyService extends Service{@Overridepublic IBinder onBind(Intent intent){return null;}@Overridepublic void onCreate(){Log.d("StartUpMyService", "onCreate");super.onCreate();}@Overridepublic void onDestroy(){Log.d("StartUpMyService", "onDestroy");super.onDestroy();}@Overridepublic void onStart(Intent intent, int startId){Log.d("StartUpMyService", "onStart");super.onStart(intent, startId);}}
定义绑定的Activity
public class MessageActivity extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.message);}}
更多相关文章
- Android 中自定义 Adapter
- Android 系统菜单与自定义菜单
- Android 基础知识、Android 进阶知识、Android 自定义 View 相关
- android自定义属性的使用
- Android 中自定义属性(attr.xml,TypedArray)的使用
- ANDROID自定义SCROLLVIEW
- 《Gradle 权威指南》读书笔记——第八章 自定义Android Gradle
- Android ndk开发时查看编译器预定义宏