我創建了一個服務,並將它放在前臺併發出通知。在服務中,我有一個計時器,打印「SERVICE STILL RUNNING」讓我知道該服務還活着。當我關閉應用程序時,服務的OnDestroy()被調用,但timmer仍然打印「SERVICE STILL RUNNING」,爲什麼?我通過調用showNotification()將該服務置於前臺。如果我沒有調用showNotification()並關閉應用程序,則服務會被破壞,而TIMMER會停止打印「SERVICE STILL RUNNING」。如何在前臺使用該服務,並在關閉應用程序時正確使用該服務。即使在應用程序關閉後,內存監視器仍會繼續顯示內存使用情況。如果我不把該服務放在前臺並關閉應用程序,內存監視器停止。此問題只發生在Android 6.0。Android服務不停止運行
MainActivity:
public class MainActivity extends Activity {
Intent service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
service = new Intent(MainActivity.this, MyService.class);
// starting Client service
service.setAction("START");
startService(service);
}
@Override
protected void onDestroy() {
super.onDestroy();
service.setAction("STOP");
stopService(service);
}
}
服務:
public class MyService extends Service {
Timer timer;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
if(intent !=null)
{
if(intent.getAction().equals("START"))
{
showNotification();
} else if(intent.getAction().equals("STOP"))
{
stopForeground(true);
stopSelf();
}
}else
{
//stopForeground(true);
//stopSelf();
}
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run()
{
Log.d("","SERVICE STILL RUNNING");
}
},1*1000,5*1000);
}
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction("new");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setTicker("Test")
.setContentText("testing")
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true).build();
startForeground(101, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("","SERVICE HAS BEEN DESTROYED!!!");
}
}
使用服務與活動http://developer.android.com/intl/es/guide/components綁定/bound-services.html – zgc7009
@ zgc7009 - 我可以通過通知在前臺綁定服務,以便Android操作系統不會終止服務? – amanda45
你看過http://developer.android.com/intl/es/reference/android/app/Service.html,它是關於通知的「本地服務」部分? – zgc7009