我的应用程序已安装,但重新启动后设备未运行。
我的服务:
package com.example.service_m;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class ServiceCode extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
for(int i=0;i<=10;i++){
Toast.makeText(getApplicationContext(), "hello world",
Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return Service.START_NOT_STICKY;
}
}
我的广播接收器:
package com.example.service_m;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ServiceStarter extends BroadcastReceiver{
@Override
public void onReceive(Context _context, Intent _intent) {
Intent service = new Intent(_context, ServiceCode.class );
_context.startService(service);
}
}
AndroidManifest
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.service_m.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<receiver android:name="com.example.service_m.ServiceStarter" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name="com.example.service_m.ServiceCode.class">
</service>
</application>
我的应用程序已安装,但在设备重新启动时未运行。 有什么问题吗? 请帮我! 我想学习制作一个后台应用程序。
最佳答案
在 list 文件中定义服务和权限
<service
android:name="com.example.service_m.ServiceCode">
</service>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
在您的接收器中使用此代码:
Intent service = new Intent(_context, ServiceCode.class );
_context.startService(service);
关于java - 我想在android中创建一个服务但我的服务没有运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25428340/