通过编程方式从任务栏android执行清除应用程序的操作

时间:2019-03-22 10:30:18

标签: android background android-lifecycle

我想在应用关闭时点击一个API。我已经在onDestroy方法中完成了api工作。这在我通过backpress退出应用程序时有效。但是如果我直接从任务栏中清除应用程序而没有使用backpress,则方法将无法运行。我现在正在寻找一种方法,当我从任务栏中清除应用程序时,该方法可以帮助我执行操作。希望大家帮忙。感谢您的支持

这是我的代码

                                     override fun onBackPressed() {
                                         logout2()
                                         super.onBackPressed()
                                     }

                                     override fun onDestroy() {
                                         logout2()
                                         super.onDestroy()
                                     }

1 个答案:

答案 0 :(得分:0)

在清单文件中,将Service的标志stopWithTask保留为false。喜欢:

 <service
    android:name="com.myapp.MyService"
    android:stopWithTask="false" />

MyService.java

public class MyService extends AbstractService {

    @Override
    public void onStartService() {
        Intent intent = new Intent(this, MyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new Notification(R.drawable.ic_launcher, "My network services", System.currentTimeMillis());
        notification.setLatestEventInfo(this, "AppName", "Message", pendingIntent);
        startForeground(MY_NOTIFICATION_ID, notification);  
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Toast.makeText(getApplicationContext(), "onTaskRemoved called", Toast.LENGTH_LONG).show();
        System.out.println("onTaskRemoved called");
        super.onTaskRemoved(rootIntent);
    }
}

AbstractService.java是扩展Sevrice的自定义类:

public abstract class AbstractService extends Service {

    protected final String TAG = this.getClass().getName();

    @Override
    public void onCreate() {
        super.onCreate();
        onStartService();
        Log.i(TAG, "onCreate(): Service Started.");
    }

    @Override
    public final int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStarCommand(): Received id " + startId + ": " + intent);
        return START_STICKY; // run until explicitly stopped.
    }

    @Override
    public final IBinder onBind(Intent intent) {
        return m_messenger.getBinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        onStopService();
        Log.i(TAG, "Service Stopped.");
    }    

    public abstract void onStartService();
    public abstract void onStopService();
    public abstract void onReceiveMessage(Message msg);

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Toast.makeText(getApplicationContext(), "AS onTaskRemoved called", Toast.LENGTH_LONG).show();
        super.onTaskRemoved(rootIntent);
    }
}