service随APP关闭而关闭

发布时间:2016-12-7 22:39:10 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"service随APP关闭而关闭",主要涉及到service随APP关闭而关闭方面的内容,对于service随APP关闭而关闭感兴趣的同学可以参考一下。

service的两种启动方式之前已经介绍过,知道startservice()方式,如果未手动停止,service不随activity关闭而关闭,但是如果APP关闭了,那么service会关闭不?会。 1:activity启动service public class MainActivity extends Activity { private Button StartServiceBut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StartServiceBut = (Button) findViewById(R.id.button); StartServiceBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, MyService.class); startService(intent); } }); } } 对应的xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="50dp" android:text="******start service******" android:gravity="center"/> </LinearLayout> 2:service的实现 public class MyService extends Service { @Override public void onCreate() { new MyThread().start(); } public class MyThread extends Thread{ @Override public void run() { while(true){ try { sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } Message msg = new Message(); msg.what = 0x0011; handler.sendMessage(msg); } } } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0x0011: Toast.makeText(MyService.this, "service", Toast.LENGTH_SHORT).show(); break; default: break; } } }; @Override public IBinder onBind(Intent intent) { return null; } } 当在设置里关闭应用时,service便停止啦!

上一篇:grep用法
下一篇:Java四种线程池的使用

相关文章

相关评论