如何在设备启动时启动Android应用程序?

13

我需要启动Android前台服务,并在设备启动时从该服务中启动活动。我已经在网上和stackoverflow上进行了广泛的搜索,并尝试了不同的建议,但很奇怪我无法使这个功能正常工作。

我不明白我做错了什么。

下面是我的项目代码和清单文件的内容。

我该如何解决问题,让这个功能在大多数Android设备上正常工作?

这是我的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kor.location.tracker">


    <uses-permission android:name="android.permission.INTERNET" ></uses-permission>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <receiver android:name="kor.location.tracker.AutoStart">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>


        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <service android:enabled="true"
            android:name="kor.location.tracker.WorkerService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE"
            />

    </application>

</manifest>

这是我的Austostart.java文件:

package kor.location.tracker;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

public class AutoStart  extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent arg1)
        {

            try {
                System.out.println("test1");
                if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
                    System.out.println("test2");
                    WorkerService.enqueueWork(context, new Intent());
                    System.out.println("test3");
                }

            }catch(Exception ex) {

                Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
            }
            /*
            Intent intent = new Intent(context, WorkerService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
            Log.i("Autostart", "started");

             */
        }
    }

这是我的服务类WorkerService.java:

package kor.location.tracker;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;

public class WorkerService  extends JobIntentService
{

    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, WorkerService.class, 104501, work);
    }
/*
    private static final String TAG = "MyService";
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
    }
*/
    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        Intent intents = new Intent(getBaseContext(),MainActivity.class);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);
        //Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        //Log.d(TAG, "onStart");
    }
/*
    @Override
    public void onStart(Intent intent, int startid)
    {
        final LocationListener mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(final Location location) {
                //your code here
                String kuku = location.getLatitude() + "=" + location.getLongitude();
                Toast.makeText(WorkerService.this, kuku, Toast.LENGTH_LONG).show();
                Log.d(TAG, kuku);

                ;
                ;
                location.getAltitude();
                location.getSpeed();
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


        try {

            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000,
                    1, mLocationListener);

        }catch (SecurityException ex){

            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
            Log.d(TAG, ex.getMessage());
        }


        Intent intents = new Intent(getBaseContext(),MainActivity.class);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
    }
    */
}

这是我的活动,但它无法启动:

package kor.location.tracker;

import android.Manifest;
import android.content.pm.PackageManager;
import android.nfc.Tag;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();


        List<String> permissions = new ArrayList<String>();

        if(getApplicationContext().checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED){
            permissions.add(Manifest.permission.INTERNET);
        }

        if(getApplicationContext().checkCallingOrSelfPermission(Manifest.permission.RECEIVE_BOOT_COMPLETED) != PackageManager.PERMISSION_GRANTED){
            permissions.add(Manifest.permission.RECEIVE_BOOT_COMPLETED);
        }

        if(getApplicationContext().checkCallingOrSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }

        if(getApplicationContext().checkCallingOrSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if(getApplicationContext().checkCallingOrSelfPermission(Manifest.permission.FOREGROUND_SERVICE) != PackageManager.PERMISSION_GRANTED){
            permissions.add(Manifest.permission.FOREGROUND_SERVICE);
        }

        if(permissions.size()>0) {

            String[] arr = new String[permissions.size()];
            permissions.toArray(arr);
            //System.out.println();
            ActivityCompat.requestPermissions(this, arr, 1);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


你的 arg1.getAction() 返回什么? - coroutineDispatcher
这个想法是它应该返回Intent.ACTION_BOOT_COMPLETED,当它这样做时,服务应该启动。但是我试图用toeast显示它的值,但是永远不会显示toast。@coroutineDispatcher - Tornike Shavishvili
4个回答

9

1- 解决从后台启动Activity的问题

在API 29中,安卓限制了从后台启动Activity。前台服务也被视为后台进程。如果您在安卓10中测试它,您的Activity可能会受到此限制的影响。

Android Q限制: https://developer.android.com/guide/components/activities/background-starts

可能的解决方案:https://dev59.com/y1IH5IYBdhLWcg3weuq6#59421118

2- 某些品牌限制应用程序在开机时启动以提高设备的启动时间。因此,应用程序需要独占权限才能在开机时启动。

可能的解决方案(程序化): https://dev59.com/1lkS5IYBdhLWcg3w25zq#49167712

对于小米用户,可以通过设置启用自动启动 https://dontkillmyapp.com/xiaomi


1
前台服务通知不应该关闭,除非您通过编程方式关闭服务或者服务崩溃。您应该通过日志找出为什么它正在关闭。这取决于情况,有时可能很难找到原因。对于小米手机,请在设置中检查自动启动权限。我也会考虑其他可能性。如果我能找到答案,我会告诉您的。 - Eren Tüfekçi
1
实际上,我不理解你的情况。当通知显示时,这意味着您的服务已经启动。因为您的前台服务创建了通知。如果您不使用前台服务显示通知,则尝试使用启动服务而不是活动。然后从此服务启动活动。 - Eren Tüfekçi
1
我的意思是,在handlework方法中启动一个前台服务。并创建一个通知,对于Android 10,将挂起意图添加到通知中,对于其他API,您可以从前台服务启动活动。如果您无法处理它,请告诉我,我认为我们将成功找到解决方案。 - Eren Tüfekçi
我在设置中检查了自动启动权限,发现我的应用程序没有开启,我已经启用了它。我将恢复所有更改并检查它。我想问一下:我启动前台服务的方式正确吗?它适用于哪些Android版本? - Tornike Shavishvili
1
在Android 10中,限制了从后台启动活动而非启动服务。因此,您可以在引导完成后启动服务。当您创建前台服务时,必须创建通知。此通知可以有一个挂起意图,在Android 10中打开活动。 - Eren Tüfekçi
显示剩余3条评论

3
在清单文件中添加了启动权限(参见下面的代码)后,广播接收器开始接收启动完成事件并成功地启动服务。为使解决方案生效(按@Eren Tüfekçi建议),我必须在手机设置中启用应用程序的自启动权限。如果有人知道如何通过编程方式启用它,请告诉我们。谢谢。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kor.location.tracker">


    <uses-permission android:name="android.permission.INTERNET" ></uses-permission>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <receiver android:name="kor.location.tracker.AutoStart"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:directBootAware="true">
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>
        </receiver>


        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <service android:enabled="true"
            android:name="kor.location.tracker.WorkerService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE"
            />

    </application>

</manifest>

在我的Android 9设备上,我不得不将 android:directBootAware="true" 添加到扩展 JobIntentServiceservice 元素中,即: <service android:enabled="true" android:directBootAware="true" android:name="kor.location.tracker.WorkerService" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" /> - Josh Hansen
我们需要将接收器的exported属性设置为true吗?为什么需要这个权限?android:permission="android.permission.BIND_JOB_SERVICE" - K Pradeep Kumar Reddy
2
如何在手机设置中启用自动启动权限?请问它在哪里? - IgorGanapolsky

1
我仍然可以在启动时启动应用程序(目标API 29)。通过使用具有意图ACTION_BOOT_COMPLETED的广播接收器。
在将我的安卓更新到荣耀品牌的9版本后,我面临的问题是引入了先进的应用程序管理,可能是为了保护电池,这阻止了我的应用程序首先接收广播。
转到“设置”>“电池”>“应用程序启动”>转到您的应用程序并取消选中“自动管理”>确保选中“自动启动”,“次要启动”,“后台运行”,然后选择“确定”。
重新启动手机并检查应用程序是否在启动时启动。希望这能帮助其他人。

1

请检查此处。通过这种方式,您想要实现的内容应该可以工作。如果无法实现,请跟踪日志以找出问题。

  public class AutoStart  extends BroadcastReceiver
        {
            @Override
            public void onReceive(Context context, Intent arg1)
            {

                try {
                    Intent intent = new Intent(context, WorkerService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);

                    }

                }catch(Exception ex) {

                    Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
                }
}
}

在服务中

public class WorkerService extends Service {
    public static final String CHANNEL_ID = "ForegroundServiceChannel";
    public static final String NEW_CHANNEL_ID = "AndroidForegroundServiceChannel";

    Notification notification;

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

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {createNotificationChannel();  //for Android Oreo above notification channel mandatory }
    }

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

        try {  

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
            {// if Android 10 create a pending intent and a full screen notification

    Intent fullScreenIntent = new Intent(this, "Your Activity".class);
    PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 2022,
            fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT); // For the activity opening when notification cliced

    notification= new NotificationCompat.Builder(this, NEW_CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Notification title")
            .setContentText("Notification Text")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_REMINDER)
            .setFullScreenIntent(fullScreenPendingIntent, true)
            .build();

    startForeground(2, notification);
}
            else
            {
//if below Android 10 created a notification for foreground service because it is mandatory
            Intent notificationIntent = new Intent(this, Your Activity.class);
            PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0022,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentText("Foreground Service")
                    .setSmallIcon(R.drawable.ic_notification)
                    .setSound(null)
                    .setContentIntent(pendingNotificationIntent)
                    .build();

             //for below Android 10 started activity
                    Intent i = new Intent(getApplicationContext(), Your Activity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                     
                    getApplicationContext().startActivity(i);
                }


            startForeground(1, notification);
        }
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(), "Foreground Service fault", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }

        return START_NOT_STICKY;
    }
   private void createNotificationChannel() {

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    NEW_CHANNEL_ID,
                    "Android Foreground Service Channel",
                    NotificationManager.IMPORTANCE_HIGH
            );

            serviceChannel.setSound(null,null);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);

        }

      else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            serviceChannel.setSound(null,null);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

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

我成功地在设备启动时启动了服务并显示了Toast。我意识到之前它没有工作是因为我的清单文件中有错误的启动权限。在我添加了权限后,问题得到了解决。 - Tornike Shavishvili

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接