Android(安卓)利用广播接收器启动服务
16lz
2021-01-26
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" > 9application10 11 12 14 1513 16 2017 18 19
转载于:https://www.cnblogs.com/A--Q/p/6694588.html
更多相关文章
- 主流移动平台分辨率
- Android为TV端助力 MediaPlayer 错误代码(error code)总结 转载
- android 实现Listview 动态删除
- Android(安卓)PopupMenu显示
- android 上传Bitmap到服务器端
- Android(安卓)通用Dialog中设置RecyclerView
- Android——Google应用移植时的包依赖关系
- Android(安卓)一键分享功能简单实现
- android:点击popupwindow以外区域 popupwindow自动消失(转载)