Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android-启动时启动服务_Java_Android_Broadcastreceiver_Intentservice - Fatal编程技术网

Java Android-启动时启动服务

Java Android-启动时启动服务,java,android,broadcastreceiver,intentservice,Java,Android,Broadcastreceiver,Intentservice,从我在Stack Exchange和其他地方看到的一切来看,我已经正确设置了一切,以便在Android操作系统启动时启动IntentService。不幸的是,它不是启动,我没有得到任何错误。也许专家们能帮上忙 舱单: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.phx.batte

从我在Stack Exchange和其他地方看到的一切来看,我已经正确设置了一切,以便在Android操作系统启动时启动IntentService。不幸的是,它不是启动,我没有得到任何错误。也许专家们能帮上忙

舱单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.phx.batterylogger"
  android:versionCode="1"
  android:versionName="1.0"
  android:installLocation="internalOnly">

<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <service android:name=".BatteryLogger"/>
    <receiver android:name=".StartupIntentReceiver">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED" />  
        </intent-filter>  
    </receiver>
</application>

</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="internalOnly">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" 
    />
<!--        <activity android:name=".MyActivity">
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER"></category> 
            </intent-filter>
       </activity> -->
        <service android:name=".Test1Service" 
                  android:label="@string/app_name"
                  >
        </service>
        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>  
        </receiver> 
    </application>
</manifest>
更新:我尝试了下面的所有建议,并添加了日志记录,如
Log.v(“BatteryLogger”,“Got to onReceive,即将启动服务”)
发送到StartupIntententReceiver的onReceive处理程序,并且不会记录任何内容。所以它甚至没有到达广播接收器

我认为我正在正确部署APK并进行测试,只是在Eclipse中运行Debug,控制台说它成功地将它安装到我的Xoom平板电脑上,地址是\BatteryLogger\bin\BatteryLogger.APK。然后,为了进行测试,我重新启动平板电脑,然后查看DDMS中的日志,并在操作系统设置中检查正在运行的服务。这些听起来都正确吗,还是我遗漏了什么?再次感谢您提供的任何帮助。

看起来非常类似,但我使用完整的软件包名称作为接收者:

<receiver android:name=".StartupIntentReceiver">

我有:

<receiver android:name="com.your.package.AutoStart"> 

我在没有完整软件包的情况下取得了成功,您知道呼叫链在哪里中断吗?如果使用
Log()
进行调试,它在什么时候不再工作


我认为这可能是出于您的意图,这一切看起来都很好。

这里是一个AutoStart应用程序的完整示例

AndroidManifest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pack.saltriver" android:versionCode="1" android:versionName="1.0">

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <receiver android:name=".autostart">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity android:name=".hello"></activity>
        <service android:enabled="true" android:name=".service" />
    </application>
</manifest>
service.java

public class autostart extends BroadcastReceiver 
{
    public void onReceive(Context context, Intent arg1) 
    {
        Intent intent = new Intent(context,service.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
        Log.i("Autostart", "started");
    }
}
public class service extends Service
{
    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
    public void onStart(Intent intent, int startid)
    {
        Intent intents = new Intent(getBaseContext(),hello.class);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
    }
}
hello.java-执行应用程序一次后,每次启动设备时都会弹出此窗口

public class hello extends Activity 
{   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
    }
}

下面的方法应该有效。我已经核实了。也许你的问题在别的地方

接收人:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
            Log.d("TAG", "MyReceiver");
            Intent serviceIntent = new Intent(context, Test1Service.class);
            context.startService(serviceIntent);
        }
    }
}
服务:

public class Test1Service extends Service {
    /** Called when the activity is first created. */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "Service created.");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "Service started.");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG", "Service started.");
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}
舱单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.phx.batterylogger"
  android:versionCode="1"
  android:versionName="1.0"
  android:installLocation="internalOnly">

<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <service android:name=".BatteryLogger"/>
    <receiver android:name=".StartupIntentReceiver">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED" />  
        </intent-filter>  
    </receiver>
</application>

</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="internalOnly">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" 
    />
<!--        <activity android:name=".MyActivity">
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER"></category> 
            </intent-filter>
       </activity> -->
        <service android:name=".Test1Service" 
                  android:label="@string/app_name"
                  >
        </service>
        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>  
        </receiver> 
    </application>
</manifest>

由于设备在启动后进入睡眠状态,您的服务可能会在完成之前关闭。您需要先获得唤醒锁。幸运的是,我们可以这样做:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}
然后,在您的服务中,确保释放唤醒锁:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }
不要忘记添加唤醒锁定权限:

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

只是为了让搜索更容易,如注释中所述,这在3.1版之后是不可能的

我找到了一种方法,可以在设备重新启动时使应用程序正常运行,请按照以下步骤操作以获得成功

AndroidManifest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission 
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".UIBootReceiver" android:enabled="true" 
    android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
     <service android:name=".class_Service" />
</application>
这是请求允许您不需要管理此应用程序的电池节省,以便您可以在后台稳定运行

在MainActivity类的onCreate()中声明此代码:

   Intent myIntent = new Intent();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        myIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        myIntent.setData(Uri.parse("package:" + 
   DeviceMovingSpeed.this.getPackageName()));
    }
    startActivity(myIntent);


你遇到了什么问题,你没有得到任何用户界面吗?这就是问题所在。你是如何知道你的服务没有启动的,你打印过日志或类似的东西吗?你不需要日志就能看到它没有运行。Android操作系统公开了运行中的服务。但是,最好使用日志记录来查看是否发生了错误。如果发生错误,我会大胆猜测它发生在context.startService()之前发送到onReceive处理程序,它永远不会显示在日志中。所以侦听器失败了(?)我添加了
Log.v(“BatteryLogger”,“Got to onReceive,即将启动服务”)
发送到onReceive处理程序,它永远不会显示在日志中。那么听者失败了(?)是什么让广播接收器在手机启动时启动的?谢谢孩子。我已经好几年没碰安卓了。抱歉@Ruchir+1提供了完整的示例。也许我应该把我的意向服务改成一个简单的老服务,这最终解决了它。问题在于我的服务是一个IntentService,而不是普通的旧服务,以及服务代码中的错误。这个答案的彻底性和安卓系统的登录帮助我解决了我的问题。如果没有活动,这也可以工作吗?onStart()回调已被弃用。您应该改为使用onStartCommand()。@mmBs这个答案已经有5年历史了,所以很明显,对您的问题进行排序有点困难,所以最好发布一个hello world示例。谢谢,但它仍然不起作用。日志甚至没有显示它能够进入StartupIntententReceiver。还有其他想法吗?您的代码在emulator中工作吗?你能在emulator中接收到intent吗?我在emulator中进行了测试,在DDMS中发现了一个错误,但看起来至少服务正在尝试启动,尽管其中没有我的
Log()
语句,并且emulator设备没有显示我的服务正在操作系统设置中运行。以下是DDMS中的错误:
System.err-在com.phx.batterylogger$1.onReceive(batterylogger.java:43)
这是否意味着问题出现在我的batterylogger服务的第43行?我也有同样的问题。你介意帮我吗?谢谢这不是真的,正如在同一个答案的评论部分所说的。一个更详细的解释来支持我的论点:我已经很久没有用android做任何事情了,但是你是对的,这是可能的。没有其他必要的论据。(我将编辑答案)