首页 > 解决方案 > 停止旧进程在jobservice android java中创建新进程

问题描述

我创建了一个作业服务,但是当它重新运行时启动新进程。我想在重新运行服务时关闭旧的然后开始新的。我的日志输出 2021-09-07 12:46:49.890 5309-5356/edu.cs4730.jobservicejobworkitemdemo D/ExampleJobService: run: 173 2021-09-07 12:46:52.775 5309-5414/edu.cs4730.jobservicejobworkitemdemo D/ ExampleJobService:运行:34 2021-09-07 12:46:52.871 5309-5345/edu.cs4730.jobservicejobworkitemdemo D/ExampleJobService:运行:184 2021-09-07 12:46:52.883 5309-5385/edu.cs4730.jobservicejobworkitemde D/ExampleJobService:运行:114 2021-09-07 12:46:52.884 5309-5366/edu.cs4730.jobservicejobworkitemdemo D/ExampleJobService:运行:154 2021-09-07 12:46:52.894 5309-5356/edu.cs4730 .jobservicejobworkitemdemo D/ExampleJobService:运行:174 2021-09-07 12:46:55.775 5309-5414/edu.cs4730.jobservicejobworkitemdemo D/ExampleJobService:运行:35 2021-09-07 12:46:55。

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    public static String id1 = "test_channel_01";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void scheduleJob(View v) {
        ComponentName componentName = new ComponentName(this, MyJobWorkService.class);
        JobInfo info = new JobInfo.Builder(123, componentName)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .setPeriodic(15 * 60 * 1000)
                .build();

        JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        int resultCode = scheduler.schedule(info);
        if (resultCode == JobScheduler.RESULT_SUCCESS) {
            Log.d(TAG, "Job scheduled");
        } else {
            Log.d(TAG, "Job scheduling failed");
        }
    }

    public void cancelJob(View v) {
        JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        scheduler.cancel(123);
        Log.d(TAG, "Job cancelled");
    }





}

MyJobWorkService.java


public class MyJobWorkService extends JobService {
    private static final String TAG = "ExampleJobService";
    private boolean jobCancelled = false;
    private Timer timer;
    int i=0;
    private NotificationManager notificationManager;
    int NOTIFICATION_ID = 234;
    String CHANNEL_ID = "my_channel_01";
    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d(TAG, "Job started");
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

      //  mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Log.i("JobWorkService", "Service Created");
        Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
        doBackgroundWork(params);

        return true;
    }

    private void doBackgroundWork(final JobParameters params) {
        new Thread(new Runnable() {
            @Override
            public void run() {


                timer = new Timer();
                // This timer task will be executed every 1 sec.
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        i++;
                        Log.d(TAG, "run: " + i);
                        sendNotification("run: " + i,"test");
                    }
                }, 0, 3000);



                Log.d(TAG, "Job finished");
               // hideNotification();

            }
        }).start();

        jobFinished(params, true);

    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d(TAG, "Job cancelled before completion");
        hideNotification();
        jobCancelled = true;
        return true;
    }

     private void sendNotification(String messageTitle,String messageBody) {
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant")
            NotificationChannel notificationChannel=new NotificationChannel("my_notification","n_channel",NotificationManager.IMPORTANCE_MAX);
            notificationChannel.setDescription("description");
            notificationChannel.setName("Channel Name");
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);
        }


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setNotificationSilent()
                .setChannelId("my_notification")
                .setColor(Color.parseColor("#3F5996"));

        //.setProgress(100,50,false);
        assert notificationManager != null;
        int m = 1;
        notificationManager.notify(m, notificationBuilder.build());
    }
    private void hideNotification() {
        notificationManager.cancel(NOTIFICATION_ID);
    }


}



标签: javaandroid

解决方案


推荐阅读