Android 利用Service BroadcastReceiver实现小例子
Activity:
1 package com.example.test; 2 3 import android.app.Activity; 4 import android.content.Context; 5 import android.content.Intent; 6 import android.content.IntentFilter; 7 import android.os.Bundle; 8 import android.view.Menu; 9 import android.view.MenuItem; 10 import android.widget.TextView; 11 /** 12 * 实现当插接电源时,手机震动并弹出消息。 13 * @author shaobn 14 * @date 2015-9-19 15 * @packege com.example.testTest 16 */ 17 public class MainActivity extends Activity { 18 private TextView text; 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_main); 23 text = (TextView) this.findViewById(R.id.textView1); 24 IntentFilter intentFilter = new IntentFilter(); 25 intentFilter.addAction(Intent.ACTION_POWER_CONNECTED); 26 MyReceiver myReceiver = new MyReceiver(); 27 registerReceiver(myReceiver,intentFilter); 28 } 29 }
BroacastReceiver:
1 package com.example.test; 2 3 import android.content.BroadcastReceiver; 4 import android.content.Context; 5 import android.content.Intent; 6 /** 7 * 8 * @author shaobn 9 * @date 2015-9-19 10 * @packege com.example.testTest 11 */ 12 public class MyReceiver extends BroadcastReceiver { 13 14 @Override 15 public void onReceive(Context context, Intent arg1) { 16 // TODO Auto-generated method stub 17 Intent intent = new Intent(); 18 intent.putExtra("msg","helloworld"); 19 intent.setClass(context,MyService.class); 20 context.startService(intent); 21 } 22 }
Service:
1 package com.example.test; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.os.IBinder; 6 import android.os.Vibrator; 7 import android.widget.Toast; 8 /** 9 * 10 * @author shaobn 11 * @date 2015-9-19 12 * @packege com.example.testTest 13 */ 14 public class MyService extends Service { 15 16 @Override 17 public IBinder onBind(Intent arg0) { 18 // TODO Auto-generated method stub 19 return null; 20 } 21 @Override 22 public void onCreate() { 23 // TODO Auto-generated method stub 24 super.onCreate(); 25 } 26 @Override 27 public int onStartCommand(Intent intent, int flags, int startId) { 28 // TODO Auto-generated method stub 29 String message = intent.getStringExtra("msg"); 30 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 31 vibrator.vibrate(2000); 32 Toast.makeText(getApplicationContext(),message,1).show(); 33 return super.onStartCommand(intent, flags, startId); 34 } 35 }
自己随手写的,程序有点简单,就不写注释了。AndroidManifest.xml中注意配置Service 以及vibrator权限。
吾宁做一叶扁舟,始航于湖边,遨游于海上,浪迹于江中。