@Override
public void onDestroy()
{
MessageService.this.stopSelf();
messageThread.isRunning = false;
System.exit(0);
super.onDestroy();
}
我在销毁方法里写上了这些代码,在其他Activity里关闭服务(stopService(new Intent(MainOptionActivity.this,MessageService.class));),试了很多代码都不行啊?
大神门  你们的见解??

解决方案 »

  1.   


    /**
     * 从服务器端获取消息
     */
    class MessageThread extends Thread
    {
    // 设置为false后,线程跳出循环并结束
    public boolean isRunning = true; public void run()
    {
    while (isRunning)
    {
    try
    {
    // 得到消息内容
    String serverMessage = getServerMessage(); if (serverMessage != null && !"".equals(serverMessage))
    {
    // 设置消息内容
    contentView.setTextViewText(R.id.text, serverMessage);
    // 为意图添加参数
    messageIntent.putExtra("message", serverMessage);
    // 将意图装入 延迟意图
    messagePendingIntent = PendingIntent.getActivity(
    MessageService.this, 0, messageIntent,
    PendingIntent.FLAG_CANCEL_CURRENT);
    // 将延迟意图装入消息
    messageNotification.contentIntent = messagePendingIntent;
    messageNotificatioManager.notify(messageNotificationID,
    messageNotification); // messageNotificatioManager.cancel(messageNotificationID-1);//新消息来后,消除之前的一条消息(只显示最新消息)
    // 配置好下条消息的id号
    messageNotificationID++;
    }
    // 休息10秒钟
    Thread.sleep(TIME);
    } catch (InterruptedException e)
    {
    e.printStackTrace();
    }
    }
    }
    }
      

  2.   

    Thread.sleep(TIME);线程还在跑,无法关闭服务的
      

  3.   

    run 函数最后打个log看看线程到底退了没
      

  4.   

    System.exit(0);去掉。还有既然要摧毁了,干嘛还在里面stop啊
      

  5.   


    我Log一下 发现  线程的运行布尔值 一直为true  我明明设置为假了   还有销毁方法一直没有运行呀?
      

  6.   

    重点是你的destroy方法都没执行,怎么关闭服务呢?
      

  7.   

    这有一个关于service类的简答代码:
    public class MyService extends Service {@Override
    public IBinder onBind(Intent intent) {    return null;
    }@Override
    public void onCreate() {
        Toast.makeText(getApplicationContext(), "MSG onCreate SERVICE", Toast.LENGTH_LONG).show();
        super.onCreate();
    }@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(), "MSG onStartCommand SERVICE", Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }@Override
    public void onDestroy() {
        Toast.makeText(getApplicationContext(), "MSG STOP SERVICE", Toast.LENGTH_LONG).show();
        super.onDestroy();
    }}
    测试这个服务
    startService(new Intent(this, MyService.class));    new Timer().schedule(new TimerTask() {        @Override
            public void run() {
                startService(new Intent(getApplicationContext(), MyService.class));
            }
        }, 5000);    new Timer().schedule(new TimerTask() {        @Override
            public void run() {
                stopService(new Intent(getApplicationContext(), MyService.class));
            }
        }, 10000);
    在manifest中添加:
    <service android:name=".MyService" />