Android java后台运行活动
我正在创建通知,并在通知中添加“addAction”。 我想在单击“addAction”时,删除通知并运行另一个代码。 我怎么能做到Android java后台运行活动,android,android-intent,android-notifications,Android,Android Intent,Android Notifications,我正在创建通知,并在通知中添加“addAction”。 我想在单击“addAction”时,删除通知并运行另一个代码。 我怎么能做到 Intent intent = new Intent(context, Activity.class); PendingIntent pi = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT); .........
Intent intent = new Intent(context, Activity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
.........
.addAction(R.drawable.eye, "View", pi)
我想在后台运行Activity.class,我的意思是此活动未打开,但此活动中的代码正在运行。
我如何做到这一点?如果你想在后台运行代码,你必须创建一个服务
Intent intent = new Intent(context, Activity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
.........
.addAction(R.drawable.eye, "View", pi)
前
服务代码
package com.javatechig.serviceexample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class HelloService extends Service {
private static final String TAG = "HelloService";
private boolean isRunning = false;
@Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
@Override
public void run() {
//Your logic that service will perform will be placed here
//In this example we are just looping and waits for 1000 milliseconds in each loop.
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
if(isRunning){
Log.i(TAG, "Service running");
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
@Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
你不可能是认真的…要在后台运行某些东西,你应该做一个服务,而不是一个活动。
Intent intent = new Intent(this, HelloService.class);
startService(intent);