Android 利用广播接收器启动服务

Android 利用广播接收器启动服务_第1张图片

 1 public class MainActivity extends Activity {
 2 
 3     private Button bt ;
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.activity_main);
 7             bt = (Button)findViewById(R.id.bt);
 8             
 9             IntentFilter filter = new IntentFilter("BT");
10             Receiver recerver = new Receiver();
11             getApplicationContext().registerReceiver(recerver, filter);
12                 
13             bt.setOnClickListener(new OnClickListener(){
14                 public void onClick(View arg0) {
15                     Intent intent = new Intent("BT");
16                     intent.setPackage(getPackageName());
17                     Bundle bundle = new Bundle();
18                     bundle.putString("say",    "Hello,I'm activity!");
19                     intent.putExtras(bundle);
20                     sendBroadcast(intent);
21                 }
22             });
23     }
24 
25 }
MainActivity
 1 public class Receiver extends BroadcastReceiver {
 2 
 3     public void onReceive(Context context, Intent intent) {
 4             String bd=intent.getStringExtra("say");
 5             Toast.makeText(context,bd+ "I'm Receiver.I will send Intent!!!", Toast.LENGTH_LONG).show();
 6             intent.setAction("myservice");
 7             context.startService(intent);
 8     }
 9 
10 }
Receiver
 1 public class MyService extends Service {
 2 
 3     @Override
 4     public IBinder onBind(Intent arg0) {
 5         // TODO Auto-generated method stub
 6         return null;
 7     }
 8     
 9     public void onCreate(){
10         Toast.makeText(MyService.this, "onCreate()", Toast.LENGTH_LONG).show();
11     }
12     public void onStart(Intent intent,int startId){
13         Toast.makeText(MyService.this, "onStart()", Toast.LENGTH_LONG).show();
14         
15     }
16     public void onDestroy(){
17         Toast.makeText(MyService.this, "onDestroy()", Toast.LENGTH_LONG).show();
18     }
19 }
MyService
 1     <application
 2         android:allowBackup="true"
 3         android:icon="@drawable/ic_launcher"
 4         android:label="@string/app_name"
 5         android:theme="@style/AppTheme" >
 6         <activity
 7             android:name=".MainActivity"
 8             android:label="@string/app_name" >
 9             
10                 
11 
12                 
13             
14         
15         
16             
17                 
18             
19         
20     
application

 

转载于:https://www.cnblogs.com/A--Q/p/6694588.html

你可能感兴趣的:(Android 利用广播接收器启动服务)