如何在后台运行Java。

huangapple go评论79阅读模式
英文:

How to run java In background

问题

如何在后台运行此代码,我的意思是,即使我切换到其他应用程序,或者回到我的安卓手机的主屏幕,甚至是锁屏,按钮仍将继续点击自己。
请帮助我。

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        button1.performClick();
    }
}, 5000);
英文:

How to run this in background , I mean even I move to other app or go to home screen of my android or close the screen , the button will still clicking itself
please help me

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
button1.performClick();
}
}, 5000);

答案1

得分: 0

以下是翻译好的部分:

需要知道的事情

我将尽量用通俗易懂的话语来详细解释,以便您更好地理解线程和异步任务的概念。

new Handler().postDelayed(new Runnable() {
   @Override
   public void run() {
     //业务逻辑
   }
}, 5000);
  1. 这是一个**阻塞方法,运行在UI线程上(我假设您是新手程序员/Android开发者)[请阅读有关线程**的内容以深入了解我的说法],
  2. 这意味着简单来说,您的应用正在在一个线程上执行一些逻辑(“工作线程”,负责在屏幕上渲染UI),
  3. 通过使用线程,您可以通过将多个任务分配给多个工作线程(“线程”)来提高应用程序的效率,但不能在后台运行您的应用程序。

如何使您的应用程序在后台工作?

Google在Android Oreo中引入了一些后台限制。因此,为了保持您的应用程序处于运行状态,您需要:

  1. 使用**前台服务并显示持续通知**。

1. 实现服务的方式应该是这样的

public class YourService extends Service {

private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id";

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

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    // 在这里执行您的任务

    startForeground();
    
    return super.onStartCommand(intent, flags, startId);
}

private void startForeground() {
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
            NOTIF_CHANNEL_ID) // 不要忘记首先创建通知通道
            .setOngoing(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(getString(R.string.app_name))
            .setContentText("服务正在后台运行")
            .setContentIntent(pendingIntent)
            .build());         
   }
}

2. 您还需要启动该服务

public class App extends Application {
    
    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this, YourService.class));
    }
}

3. 在AndroidManifest.xml的“application”标签中添加您的服务

<service android:name=".YourService"/>

4. 并在“manifest”标签中添加此权限请求(如果API级别为28或更高)

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

通过这种方式,您可以将您的服务保持在后台运行。我建议您阅读文章、查看GitHub仓库,并多加实践以提高Android开发技能 如何在后台运行Java。

英文:

Things to know

I will try to elaborate as much as I can in a layman terms so that you have a better grasp the Idea of Threads and async tasks

new Handler().postDelayed(new Runnable() {
   @Override
   public void run() {
     //business logic
   }
}, 5000);
  1. is an Blocking method, which runs on the UI thread (I am supposing you are new to programming/android)[please read about Threads to understand what I am saying in deapth],
  2. which means, in short, your application is executing some logic on the thread ("A worker" which is responsible for the rendering the UI on-screen),
  3. By using Threads you can achieve efficiency in your application by dividing multiple tasks to multiple workers "Threads" but you can't run your application in the background.

How to make your application work in the background?

Google introduced some background limitations in Android Oreo. so to keep your application alive you need

  1. foreground service by showing an ongoing notification.

1. The way you should implement service is like

public class YourService extends Service {

private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = &quot;Channel_Id&quot;;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    // do your jobs here

    startForeground();
    
    return super.onStartCommand(intent, flags, startId);
}

private void startForeground() {
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
            NOTIF_CHANNEL_ID) // don&#39;t forget create a notification channel first
            .setOngoing(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(&quot;Service is running background&quot;)
            .setContentIntent(pendingIntent)
            .build());         
   }
}

2. Also you need to start the service

public class App extends Application {

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

        startService(new Intent(this, YourService.class));
    }
}

3. Add your service in the "application" tag of your AndroidManifest.xml

&lt;service android:name=&quot;.YourService&quot;/&gt;

4. And also this permission request in the "manifest" tag (if API level 28 or higher)

&lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE&quot;/&gt;

In this way, you can keep your service in the background. I suggest you read articles and see GitHub repositories, and also practice practice practice a lot to be good at Android 如何在后台运行Java。

huangapple
  • 本文由 发表于 2020年9月7日 00:57:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63766672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定