मेरे पास एक सेवा के अंदर एक धागा है और मैं अपने मुख्य गतिविधि वर्ग पर buttonStop
दबाते समय थ्रेड को रोकने में सक्षम होना चाहता हूं।किसी सेवा के अंदर एक थ्रेड को रोकना
मेरी मुख्य गतिविधि कक्षा में मेरे पास है:
public class MainActivity extends Activity implements OnClickListener {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class));
break;
}
}
}
और मेरी सेवा कक्षा में मेरे पास है:
public class MyService extends Service {
...
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
int icon = R.drawable.myicon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "notification title", "notification message", pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
...
}
@Override
public void onStart(Intent intent, int startid) {
Thread mythread= new Thread() {
@Override
public void run() {
while(true) {
MY CODE TO RUN;
}
}
}
};
mythread.start();
}
}
क्या सबसे अच्छा mythread
को रोकने के लिए तरीका है?
यह भी तरीका है कि मैंने stopService(new Intent(this, MyService.class));
द्वारा सेवा को रोक दिया है?
जब मैं 'बटनस्टॉप' दबाता हूं और उसे सर्विसेज में पास करता हूं तो मैं बूलियन चर बदल सकता हूं? – TJ1
आपको ऐसा करने की ज़रूरत नहीं है, 'stopService()', 'onDestroy()' सेवा को कॉल करके, तब बुलाया जाएगा, बूलियन झूठा होगा –
वास्तव में मुझे कोड को रोकने में सक्षम होना चाहिए चल रहा है ('मेरा कोड चलाने के लिए'), इसलिए जब मैं 'बटनस्टॉप' दबाता हूं तो मुझे 'रनिंग' को बदलने में सक्षम होना चाहिए। – TJ1