【问题标题】:how can I finish Previous Service When Its new Instance is created创建新实例时如何完成以前的服务
【发布时间】:2026-01-05 15:00:02
【问题描述】:

每当创建 Main_Activity 时,也会创建服务,但之前的服务没有完成我想在创建新服务时完成旧服务
这是我的主类,每当创建主活动时,我都会在其中调用我的服务

Main_Activity 类

        package com.example.pushtrial;

        import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.view.Menu;
        import android.view.MenuItem;

        public class MainActivity extends Activity {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);


            }

            @Override
            public void onDestroy()
            {
                super.onDestroy();
                //stopService(this.getIntent());
                Intent intent = new Intent(this, MyService.class);
                startService(intent);

            }
            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();
                if (id == R.id.action_settings) {
                    return true;
                }
                return super.onOptionsItemSelected(item);
            }
        }

这是我的服务类:

package com.example.pushtrial;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
    private static final String TAG = "MyService";
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {

        super.onCreate();
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
    }



    @Override
    public void onStart(Intent intent, int startid) {


        Log.d(TAG, "onStart");
        //new Timer().schedule(func(), "5000");// 24 hours ----> 86400
        new CountDownTimer(30000, 1000) {

             public void onTick(long millisUntilFinished) {
                 Log.d(TAG, "seconds remaining: " + millisUntilFinished / 1000);
                 //mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
             }

             public void onFinish() {
                 Log.d(TAG, "Done!");
                 func();
             }
          }.start();
        //new Timer().schedule(func(),120000);
        //player.start();
    }
    public void func()
    {
        Intent myIntent = new Intent(this, SecondActivity.class);//MainActivity.class
        myIntent.putExtra("FromNotification", true);
        PendingIntent myPendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);

        Notification myNotification  = new Notification.Builder(this)
            .setContentTitle("Event App")
            .setContentText("Hey, [Event App] is missing you! Got a minute?")
            .setSmallIcon(R.drawable.icon)
            .setContentIntent(myPendingIntent)
            .setAutoCancel(true)
            .build();//.addAction(R.drawable.icon, "Start Service", null)myPendingIntent

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0, myNotification); 


    }
}

SecondActivity.class

package com.example.pushtrial;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

【问题讨论】:

  • 什么是以前的服务?你有两个服务吗?只能看到MyService...第二个是什么?
  • 不...我的意思是说,每当我打开我的活动时,我的服务就会启动一个新服务。例如我打开我的活动两次然后两次 MyService 分别启动...
  • 不,服务是单例的:你不能有两个 MyService 实例单独启动

标签: android eclipse service android-service development-environment


【解决方案1】:

正如@pskink 所说,您没有两个MyService 实例。发生的情况是 onStart() 在同一个实例上被多次调用。

如果您想防止多个CountDownTimers 并行运行,那么您需要将代码添加到您的Service 以跟踪当前正在运行的CountDownTimer,然后杀死它并启动一个新的,或者如果已经有一个请求正在运行,则忽略第二个请求以启动一个。

【讨论】:

    最近更新 更多