Android(安卓)之开机启动Service
16lz
2021-12-04
配置文件如下:
定义广播接收器:
定义后台服务类:
定义绑定的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之自定义ProgressBar
- Android(安卓)中自定义 Adapter
- Android(安卓)AnimationDrawable动画实例
- Android(安卓)studio build inished with non-zero exit value 1
- EditText设置不自动获取焦点,点击后才获取,并弹出软键盘
- WebView中的视频播放
- Android(安卓)系统菜单与自定义菜单
- Android原生(Native)C开发之二 framebuffer篇
- Android(安卓)Animation学习笔记