服务无法启动电话重启 - Android

时间:2015-03-11 08:29:26

标签: android android-service android-broadcast

在过去的几个小时里,我一直在努力解决这个问题,在这里查看各种代码示例,但仍然没有找到解决方案。

我希望在应用启动时启动服务,并且当手机重启时,服务应该自动重启,而无需启动应用。 (重新启动手机时,无法显示吐司或日志)。请参阅下面的代码:

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, MyService.class);
    startService(intent);
}

MyService.java

public class MyService extends Service {
 @Override
 public IBinder onBind(Intent intent) {
    return null;
 } 

 @Override
 public int onStartCommand(Intent intent, int flags, int startid){
    Toast.makeText(this, "Service Running ...", Toast.LENGTH_LONG).show();
    Log.v("Service","Service Running ...");

    return super.onStartCommand(intent, flags, startid);
 }
}

Autostart.java

public class Autostart extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
    Intent myIntent = new Intent(context, MyService.class);
    context.startService(myIntent);
 }
}

的AndroidManifest.xml

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

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <receiver
        android:name=".Autostart"
        android:enabled="true"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

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

</application>
</manifest>

1 个答案:

答案 0 :(得分:0)

这似乎是小米上的 bug 。我没有遇到任何其他设备的问题