首先Service是干嘛的
就是你Activity,finish之后你创建的Service还不会死,注意关闭软件这里是finish就是返回操作,不是清理后台,这时候你可以让用户干别的,你的软件依然可以在后台运行,这是保活吗?不是。这只是可以让你的软件在后台运行,手机有电池保护,或者锁屏了,或者用户清理了后台,你的service都会失效。如何保活我过几天会发出来,你可以直接在我的博客里找。
有人就问了,你这功能Thread也可以实现,要这东西干嘛。你想你搞个Thread肯定要start和stop吧,你Activity都关了。怎么stop,你再打开你的软件你会发现之前thread的内存地址丢了,关不了了。Activity很难对Thread进行控制,当Activity被销毁之后,就没有任何其它的办法可以再重新获取到之前创建的子线程的实例
然后就要搞一个东西类似Activity一样的东西去在后台运行,那就是Service,在Service里创建Thread,Activity重新打开执行
stopService(new Intent(MainActivity.this,MainService.class));
直接把Service关了,Service一关就会调用这个重写的方法
//Service被关闭之前回调 @Override public void onDestroy() { thread.interrupt(); Log.i(TAG, "thread stopped"); super.onDestroy(); }
thread.interrupt()就可以把thread关了
MainService代码
/** * Created by Mr.Chan * Time 2022-11-07 * Blog https://www.cnblogs.com/Frank-dev-blog/ */ public class MainService extends Service { private final String TAG = "TestService1"; private Thread thread; //必须要实现的方法 @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind方法被调用!"); return null; } //Service被创建时调用 @Override public void onCreate() { Log.i(TAG, "thread have been init ed"); thread=new Thread(new Runnable() { @Override public void run() { int i = 0; //todo while (!thread.isInterrupted()){ workTime(1000); Log.e("Service:", String.valueOf(++i)); } } }); super.onCreate(); } //Service被启动时调用 @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "thread started"); thread.start(); return super.onStartCommand(intent, flags, startId); } //Service被关闭之前回调 @Override public void onDestroy() { thread.interrupt(); Log.i(TAG, "thread stopped"); super.onDestroy(); } private static void workTime(long ms) { final long l = System.currentTimeMillis(); while (System.currentTimeMillis() <= l + ms) { } } }
Manifest
<service android:name=".MainService" android:exported="true"> <intent-filter> <action android:name="com.jay.example.service.TEST_SERVICE1"/> </intent-filter> </service>
MainActivity
public class MainActivity extends AppCompatActivity { private Thread thread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Log.e("hello", String.valueOf(thread.getState())); //thread.start(); startService(new Intent(MainActivity.this,MainService.class)); } }); findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //thread.interrupt(); //Log.e("hello", String.valueOf(thread.getState())); stopService(new Intent(MainActivity.this,MainService.class)); } }); }
按钮自己建,这都不会,别学了
Github地址 下载前给star
标签:Service,thread,void,Override,Android,方法,public,Log From: https://www.cnblogs.com/Frank-dev-blog/p/16866165.html