1.service,startservice
在xml中
<service android:name="LogService" />
java代码
public class LogService extends Service { private int time=0; Handler handler = new Handler(); private Runnable runnable = new Runnable() { @Override public void run() { time++; Log.w("************", time+"副程序"); handler.postDelayed(this, 1000); } }; @Override public IBinder onBind(Intent intent) { Log.w("************", "in onBind"); return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { //处理逻辑 Log.w("************", "in onStartCommand"); handler.postDelayed(runnable, 1000); return super.onStartCommand(intent, flags, startId); } @Override public void onCreate() { super.onCreate(); Log.w("************", "in onCreate"); } @Override public void onDestroy() { handler.removeCallbacks(runnable); Intent intent = new Intent(); intent.setAction("demo.destroy"); intent.setComponent( new ComponentName( "luoy.com.servicebackstage" , "luoy.com.servicebackstage.MyReceiver") ); sendBroadcast(intent); Log.w("************", "in onDestroy"); super.onDestroy(); } }
启动
startService(intent);
停止
stopService(intent);
2. BroadcastReceiver静态注册+动态注册
xml中
<receiver android:name=".MyReceiver" android:enabled="true" android:exported="true"> <intent-filter android:priority="100"> <action android:name="android.intent.action.CLOSE_SYSTEM_DIALOGS" /> <action android:name="android.intent.action.SCREEN_OFF" /> <action android:name="android.intent.action.SCREEN_ON" /> <action android:name="demo.destroy" /> </intent-filter> </receiver>
java代码
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (intent.getAction().equals("demo.destroy")) { Intent sevice = new Intent(context, LogService.class); context.startService(sevice); Log.w("************", "onReceive"); } else if (Intent.ACTION_SCREEN_ON.equals(action)) { Log.w("************", "screen on"); } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { Log.w("************", "screen off"); } else if (Intent.ACTION_USER_PRESENT.equals(action)) { Log.w("************", "screen unlock"); } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) { Log.i("************", " receive Intent.ACTION_CLOSE_SYSTEM_DIALOGS"); } } }
启动
Intent intent = new Intent(); intent.setAction("demo.destroy"); intent.setComponent( new ComponentName( "luoy.com.servicebackstage" , "luoy.com.servicebackstage.MyReceiver") ); sendBroadcast(intent);
动态注册
IntentFilter recevierFilter=new IntentFilter(); recevierFilter.addAction(Intent.ACTION_SCREEN_ON); recevierFilter.addAction(Intent.ACTION_SCREEN_OFF); MyReceiver receiver=new MyReceiver(); 开启 registerReceiver(receiver, recevierFilter);
关闭
unregisterReceiver(receiver);