如何在后台连续运行任务?

问题描述 投票:0回答:1

我正在后台运行一个函数,但是当我来到前台而不重新启动时,我希望继续运行它。首先有可能吗?我正在RN(android)中执行此操作。

android react-native background-process
1个回答
0
投票

活动:

 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);
}
}
© www.soinside.com 2019 - 2024. All rights reserved.