<質問事項>
ServiceでThread処理するコードを書いています。コード中で、
Threadが稼働しているときに、Serviceを停止し、併せてThreadのタスクも破棄したいと考えています。ServiceとThreadの両方を同時に停止、破棄するには、どのような方法があるでしょうか?
<現状>
Service内でThreadを生成して処理させると、Serviceとは別スレッドになってしまい、Serviceを停止してもThreadのタスクが破棄されず、処理し続けてしまいます。
以下、コードを記載しますので、ろしくお願いします。
<MainActivity.java>
MainActivity
1public class MainActivity extends AppCompatActivity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 8 Button btn_start = findViewById(R.id.btn_start); 9 Button btn_stop = findViewById(R.id.btn_stop); 10 final Intent intent = new Intent(this,MyService.class); 11 12 btn_start.setOnClickListener(new View.OnClickListener(){ 13 @Override 14 public void onClick(View view) { 15 if(Build.VERSION.SDK_INT >=26){ 16 startForegroundService(intent); 17 }else{ 18 startService(intent); 19 } 20 } 21 }); 22 23 btn_stop.setOnClickListener(new View.OnClickListener(){ 24 @Override 25 public void onClick(View view) { 26 stopService(intent); 27 } 28 }); 29 30 } 31}
<MyService.java>
MyService
1public class MyService extends Service { 2 public MyService() { 3 } 4 5 public int onStartCommand(Intent intent,int flags,int startId){ 6 Notification notification; 7 Intent intent_Main = new Intent(this,MainActivity.class); 8 PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent_Main,0); 9 NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"id"); 10 notification = builder.setSmallIcon(R.drawable.notification_icon) 11 .setContentTitle("NotificationTitle") 12 .setContentText("NotificationContent") 13 .setContentIntent(pendingIntent) 14 .build(); 15 16 if(Build.VERSION.SDK_INT >=26){ 17 int importance = NotificationManager.IMPORTANCE_LOW; 18 NotificationChannel channel = new NotificationChannel("id","name",importance); 19 NotificationManager manager = getSystemService(NotificationManager.class); 20 manager.createNotificationChannel(channel); 21 startForeground(2,notification); 22 }else{ 23 notification = builder.setPriority(NotificationCompat.PRIORITY_LOW).build(); 24 NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this); 25 managerCompat.notify(1,notification); 26 } 27 28 new Thread(new Runnable(){ 29 @Override 30 public void run() { 31 for(int i=0;i<100;i++){ 32 try { 33 sleep(1000); 34 } catch (InterruptedException e) { 35 e.printStackTrace(); 36 } 37 Log.d("MSG","IN THREAD"); 38 } 39 } 40 }).start(); 41 42 return START_NOT_STICKY; 43 } 44 45 @Override 46 public IBinder onBind(Intent intent) { 47 return null; 48 } 49}
回答1件
あなたの回答
tips
プレビュー