如何在后台运行java

rkttyhzu  于 2021-07-04  发布在  Java
关注(0)|答案(1)|浏览(341)

如何在后台运行这个,我的意思是即使我移动到其他应用程序或进入我的android主屏幕或关闭屏幕,按钮仍然会点击自己请帮助我

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

sirbozc51#

要知道的事情
我将尽量用外行的术语来阐述,以便您更好地掌握线程和异步任务的概念

new Handler().postDelayed(new Runnable() {
   @Override
   public void run() {
     //business logic
   }
}, 5000);

是一个 Blocking 方法,该方法在ui线程上运行(我假设您是编程/android新手)[请阅读关于线程的内容以理解我在deapth中所说的内容],
简而言之,这意味着您的应用程序正在线程上执行某些逻辑(“一个工人”,负责在屏幕上呈现ui),
通过使用线程,您可以通过将多个任务划分为多个工作线程来提高应用程序的效率,但您不能在后台运行应用程序。
如何让你的申请在后台工作?
谷歌在android oreo中引入了一些背景限制。所以为了让你的应用程序保持活力,你需要 foreground service by showing an ongoing notification. 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){

    // 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't forget create a notification channel first
            .setOngoing(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(getString(R.string.app_name))
            .setContentText("Service is running background")
            .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:)

相关问题