首页 > 解决方案 > 如何在后台和前台连续运行任务?

问题描述

我正在后台运行一个函数,但是当我来到前台而不重新启动时,我想继续运行它。首先这可能吗?我在 RN (android) 中这样做。

下面我发布来自 BackgroundService 代码 编辑的代码:

public class BackgroundService extends Service {

private static final int SERVICE_NOTIFICATION_ID = 12345;
private static final String CHANNEL_ID = "headless_task";

private Handler handler = new Handler();
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
        Context context = getApplicationContext();
        Intent myIntent = new Intent(context, BackgroundEventService.class);

        context.startService(myIntent);
        //HeadlessJsTaskService.acquireWakeLockNow(context);
        //handler.postDelayed(runnableCode, 2000);

    }
};

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "headless_task", importance);
        channel.setDescription("CHANEL DESCRIPTION");
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public void onDestroy() {
    super.onDestroy();
    this.handler.removeCallbacks(this.runnableCode);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.handler.post(this.runnableCode);
    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("myapp").setContentText("Running...").setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(contentIntent).setOngoing(true).build();
    startForeground(SERVICE_NOTIFICATION_ID, notification);
    return START_STICKY;
}

}

标签: androidreact-nativebackground-process

解决方案


活动:

 public class MyActivity extends Activity {

    private Intent serviceIntent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Start Foreground Service
        serviceIntent = new Intent(this, MyService.class);
        serviceIntent.putExtra("name", "ahmet vefa saruhan");
        startService(serviceIntent);
        findViewById(R.id.textview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Stop Foreground Service
                stopService(new Intent(getApplicationContext(),MyService.class));
            }
        });
    }
}

服务等级

public class MyService extends Service {

private String myaction;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("MYSERVICE STATUS: "," ONSTARTCOMMAND action : " + ((intent != null && intent.getStringExtra("name") != null) ? intent.getStringExtra("name") : "yok") + " OLD ACTION : "+(myaction != null ? myaction : "yok"));
    Log.d("MYTHREAD name : ",Thread.currentThread().getName());
    //intent.putExtra("name","isim değişti");
    myaction = (intent != null) ? intent.getAction() : null;
    return START_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();
   Log.d("MYSERVICE STATUS: "," ONCREATED");
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground()
{
    String NOTIFICATION_CHANNEL_ID = "example.permanence";
    String channelName = "Background Service";
    NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    assert manager != null;
    manager.createNotificationChannel(chan);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    Notification notification = notificationBuilder.setOngoing(true)
            .setContentTitle("App is running in background")
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
    startForeground(2, notification);
}

@Override
public void onDestroy() {
    Log.d("MYSERVICE STATUS: "," ONDESTROYED");
    super.onDestroy();
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    Log.d("MYSERVICE STATUS: "," onTaskRemoved");
    super.onTaskRemoved(rootIntent);
}
}

推荐阅读