android - 如何在后台和前台连续运行任务?
问题描述
我正在后台运行一个函数,但是当我来到前台而不重新启动时,我想继续运行它。首先这可能吗?我在 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;
}
}
解决方案
活动:
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);
}
}
推荐阅读
- ruby-on-rails - 如何在产量块中调用枚举器的下一个
- javascript - React:如何改变变量的状态?
- react-admin - 在 react-admin 登录页面上禁用红色警告消息的任何解决方法?
- sql - 使用 SQL 将数字转换为相应的文本
- java - 将数组作为环境变量传递给 jboss 的standalone.xml
- java - 如何在java中的一个包中创建两个以上的类?
- javascript - 模式密码页面,如果正确,则使用 cookie 保存
- python - 数据 API:ValueError:使用数据集作为输入时不支持“y”参数
- azure - Web api生成.rdlc报告,通过rest api传递数据
- r - 如何修复错误 dim(X) 必须具有正长度 R