如何在设备启动时启动android应用程序? [英] How can I start android application on device boot?

查看:69
本文介绍了如何在设备启动时启动android应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要启动android前台服务,并在设备启动时从该服务启动活动.我已经广泛地搜索了web和stackoverflow并尝试了不同的建议,但是很奇怪我无法使此功能正常工作.

I have need to start android foreground service, and launch activity from that service on device boot. I have extensively searched web and stackoverflow and tried different suggestions but it is very strange that I can not make this functionality work.

我不明白自己在做什么.

I can not understand what I am doing wrong.

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

Below is the code from my project and the content of manifest file.

我做错了什么以及如何解决,可以在大多数android设备上使用的功能?

what I am doing wrong and how to solve it, the functionality to work on most android devices?

这是我的AndroidManifest.xml:

This is my 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:

This is my 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:

This is my service class 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");
    }
    */
}

这是我尚未开始的活动:

And this is my activity that is not getting launched:

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);
    }
}

推荐答案

在清单文件中添加了启动权限(请参见下面的代码)后,BroadcastReceiver开始获取启动完成事件,并且该服务已成功启动.为使该解决方案有效(如@ErenTüfekçi所建议),我必须在我的应用程序的电话设置中启用自动启动权限.如果有人有解决方案,如何以编程方式启用它,请告诉我们.谢谢.

After I added the boot permissions in manifest file (see code below), BroadcastReceiver started to get boot completed event and the service is starting successfully. For the solution to work (as suggested by @Eren Tüfekçi) I had to enable auto start permission in phone settings for my application. If anyone has a solution, how to enable it programmatically, please let us know. Thank you.

<?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应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆