Java 在创建从应用程序扩展的类时在中注册广播接收器
我正在开发一个应用程序,每15分钟测试服务器上的状态并推送通知,我使用了Java 在创建从应用程序扩展的类时在中注册广播接收器,java,android,broadcastreceiver,alarmmanager,Java,Android,Broadcastreceiver,Alarmmanager,我正在开发一个应用程序,每15分钟测试服务器上的状态并推送通知,我使用了报警管理器,广播接收器和意向服务。 每件事都很顺利,当应用程序运行或在后台时,我从服务器上完美地获得了这种状态,直到我将其从最近的应用程序中删除,所有事情都停止了,无法从服务器上获得这种状态。 我搜索。。。什么也得不到,但我的朋友告诉我,在创建类extend from应用程序时,我必须注册我的广播接收器 我不知道怎么做。。所以我需要帮助 主要活动类 public class MainActivity extends AppC
报警管理器
,广播接收器
和意向服务
。
每件事都很顺利,当应用程序运行或在后台时,我从服务器上完美地获得了这种状态,直到我将其从最近的应用程序中删除,所有事情都停止了,无法从服务器上获得这种状态。
我搜索。。。什么也得不到,但我的朋友告诉我,在创建类extend from应用程序时,我必须注册我的广播接收器
我不知道怎么做。。所以我需要帮助
主要活动类
public class MainActivity extends AppCompatActivity {
static TextView TvText;
Button Btn11, Btn22;
AlarmManager alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
TvText = (TextView) findViewById(R.id.tv_Text);
Btn11 = (Button) findViewById(R.id.btn_11);
Btn22 = (Button) findViewById(R.id.btn_22);
Btn22.setEnabled(false);
}
public void Btn11OC(View view) {
scheduleAlarm();
Btn11.setEnabled(false);
Btn22.setEnabled(true);
}
public void Btn22OC(View view) {
if (alarm!= null) {
cancelAlarm();
}
Btn11.setEnabled(true);
Btn22.setEnabled(false);
}
// Setup a recurring alarm every half hour
public void scheduleAlarm() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), broadtest.class);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, broadtest.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
900000L, pIntent);
}
public void cancelAlarm() {
Intent intent = new Intent(getApplicationContext(), broadtest.class);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, broadtest.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(pIntent);
}
}
public class broadtest extends WakefulBroadcastReceiver {
public static final int REQUEST_CODE = 12345;
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyService.class);
context.startService(i);
}
}
public class AppController extends Application {
@Override
public void onCreate() {
super.onCreate();
}
}
public class MyService extends IntentService {
static int NOTIFICATION_ID = 0;
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
String url = "http://test.com/testts.php";
// Tag used to cancel the request
String tag_string_req = "string_req";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Volley Log", response);
Toast.makeText(MyService.this, response, Toast.LENGTH_SHORT).show();
if (response.equals("0")){
sendNotification("Titel Test 1111", "Body Test 1111");
}else if (response.equals("1")){
sendNotification("Titel Test 2222", "Body Test 2222");
}else {
sendNotification("Titel Test 3333", "Body Test 3333");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MyService.this, error.toString(), Toast.LENGTH_SHORT).show();
VolleyLog.d("Volley Log", "Error: " + error.getMessage());
}
});
// Adding request to request queue
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
// Setup periodic alarm every 5 seconds
}
private void sendNotification(String title, String messageBody) {
long[] pattern = {500,500,500,500,500,500,500,500,500};
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(alarmSound)
.setLights(Color.BLUE, 500, 500)
.setVibrate(pattern);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (NOTIFICATION_ID > 1073741824) {
NOTIFICATION_ID = 0;
}
notificationManager.notify(NOTIFICATION_ID++, notificationBuilder.build());
}
}
宽频广播接收机
public class MainActivity extends AppCompatActivity {
static TextView TvText;
Button Btn11, Btn22;
AlarmManager alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
TvText = (TextView) findViewById(R.id.tv_Text);
Btn11 = (Button) findViewById(R.id.btn_11);
Btn22 = (Button) findViewById(R.id.btn_22);
Btn22.setEnabled(false);
}
public void Btn11OC(View view) {
scheduleAlarm();
Btn11.setEnabled(false);
Btn22.setEnabled(true);
}
public void Btn22OC(View view) {
if (alarm!= null) {
cancelAlarm();
}
Btn11.setEnabled(true);
Btn22.setEnabled(false);
}
// Setup a recurring alarm every half hour
public void scheduleAlarm() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), broadtest.class);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, broadtest.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
900000L, pIntent);
}
public void cancelAlarm() {
Intent intent = new Intent(getApplicationContext(), broadtest.class);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, broadtest.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(pIntent);
}
}
public class broadtest extends WakefulBroadcastReceiver {
public static final int REQUEST_CODE = 12345;
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyService.class);
context.startService(i);
}
}
public class AppController extends Application {
@Override
public void onCreate() {
super.onCreate();
}
}
public class MyService extends IntentService {
static int NOTIFICATION_ID = 0;
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
String url = "http://test.com/testts.php";
// Tag used to cancel the request
String tag_string_req = "string_req";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Volley Log", response);
Toast.makeText(MyService.this, response, Toast.LENGTH_SHORT).show();
if (response.equals("0")){
sendNotification("Titel Test 1111", "Body Test 1111");
}else if (response.equals("1")){
sendNotification("Titel Test 2222", "Body Test 2222");
}else {
sendNotification("Titel Test 3333", "Body Test 3333");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MyService.this, error.toString(), Toast.LENGTH_SHORT).show();
VolleyLog.d("Volley Log", "Error: " + error.getMessage());
}
});
// Adding request to request queue
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
// Setup periodic alarm every 5 seconds
}
private void sendNotification(String title, String messageBody) {
long[] pattern = {500,500,500,500,500,500,500,500,500};
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(alarmSound)
.setLights(Color.BLUE, 500, 500)
.setVibrate(pattern);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (NOTIFICATION_ID > 1073741824) {
NOTIFICATION_ID = 0;
}
notificationManager.notify(NOTIFICATION_ID++, notificationBuilder.build());
}
}
AppController类
public class MainActivity extends AppCompatActivity {
static TextView TvText;
Button Btn11, Btn22;
AlarmManager alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
TvText = (TextView) findViewById(R.id.tv_Text);
Btn11 = (Button) findViewById(R.id.btn_11);
Btn22 = (Button) findViewById(R.id.btn_22);
Btn22.setEnabled(false);
}
public void Btn11OC(View view) {
scheduleAlarm();
Btn11.setEnabled(false);
Btn22.setEnabled(true);
}
public void Btn22OC(View view) {
if (alarm!= null) {
cancelAlarm();
}
Btn11.setEnabled(true);
Btn22.setEnabled(false);
}
// Setup a recurring alarm every half hour
public void scheduleAlarm() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), broadtest.class);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, broadtest.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
900000L, pIntent);
}
public void cancelAlarm() {
Intent intent = new Intent(getApplicationContext(), broadtest.class);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, broadtest.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(pIntent);
}
}
public class broadtest extends WakefulBroadcastReceiver {
public static final int REQUEST_CODE = 12345;
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyService.class);
context.startService(i);
}
}
public class AppController extends Application {
@Override
public void onCreate() {
super.onCreate();
}
}
public class MyService extends IntentService {
static int NOTIFICATION_ID = 0;
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
String url = "http://test.com/testts.php";
// Tag used to cancel the request
String tag_string_req = "string_req";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Volley Log", response);
Toast.makeText(MyService.this, response, Toast.LENGTH_SHORT).show();
if (response.equals("0")){
sendNotification("Titel Test 1111", "Body Test 1111");
}else if (response.equals("1")){
sendNotification("Titel Test 2222", "Body Test 2222");
}else {
sendNotification("Titel Test 3333", "Body Test 3333");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MyService.this, error.toString(), Toast.LENGTH_SHORT).show();
VolleyLog.d("Volley Log", "Error: " + error.getMessage());
}
});
// Adding request to request queue
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
// Setup periodic alarm every 5 seconds
}
private void sendNotification(String title, String messageBody) {
long[] pattern = {500,500,500,500,500,500,500,500,500};
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(alarmSound)
.setLights(Color.BLUE, 500, 500)
.setVibrate(pattern);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (NOTIFICATION_ID > 1073741824) {
NOTIFICATION_ID = 0;
}
notificationManager.notify(NOTIFICATION_ID++, notificationBuilder.build());
}
}
MyService类
public class MainActivity extends AppCompatActivity {
static TextView TvText;
Button Btn11, Btn22;
AlarmManager alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
TvText = (TextView) findViewById(R.id.tv_Text);
Btn11 = (Button) findViewById(R.id.btn_11);
Btn22 = (Button) findViewById(R.id.btn_22);
Btn22.setEnabled(false);
}
public void Btn11OC(View view) {
scheduleAlarm();
Btn11.setEnabled(false);
Btn22.setEnabled(true);
}
public void Btn22OC(View view) {
if (alarm!= null) {
cancelAlarm();
}
Btn11.setEnabled(true);
Btn22.setEnabled(false);
}
// Setup a recurring alarm every half hour
public void scheduleAlarm() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), broadtest.class);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, broadtest.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
900000L, pIntent);
}
public void cancelAlarm() {
Intent intent = new Intent(getApplicationContext(), broadtest.class);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, broadtest.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(pIntent);
}
}
public class broadtest extends WakefulBroadcastReceiver {
public static final int REQUEST_CODE = 12345;
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyService.class);
context.startService(i);
}
}
public class AppController extends Application {
@Override
public void onCreate() {
super.onCreate();
}
}
public class MyService extends IntentService {
static int NOTIFICATION_ID = 0;
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
String url = "http://test.com/testts.php";
// Tag used to cancel the request
String tag_string_req = "string_req";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Volley Log", response);
Toast.makeText(MyService.this, response, Toast.LENGTH_SHORT).show();
if (response.equals("0")){
sendNotification("Titel Test 1111", "Body Test 1111");
}else if (response.equals("1")){
sendNotification("Titel Test 2222", "Body Test 2222");
}else {
sendNotification("Titel Test 3333", "Body Test 3333");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MyService.this, error.toString(), Toast.LENGTH_SHORT).show();
VolleyLog.d("Volley Log", "Error: " + error.getMessage());
}
});
// Adding request to request queue
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
// Setup periodic alarm every 5 seconds
}
private void sendNotification(String title, String messageBody) {
long[] pattern = {500,500,500,500,500,500,500,500,500};
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(alarmSound)
.setLights(Color.BLUE, 500, 500)
.setVibrate(pattern);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (NOTIFICATION_ID > 1073741824) {
NOTIFICATION_ID = 0;
}
notificationManager.notify(NOTIFICATION_ID++, notificationBuilder.build());
}
}
公共类MyService扩展了IntentService{
静态int通知_ID=0;
公共MyService(){
超级(“我的服务”);
}
@凌驾
受保护的手部内容无效(意图){
字符串url=”http://test.com/testts.php";
//用于取消请求的标记
String tag_String_req=“String_req”;
StringRequest strReq=新的StringRequest(Request.Method.GET,
url,新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
日志d(“截击日志”,响应);
Toast.makeText(MyService.this,response,Toast.LENGTH_SHORT.show();
if(响应等于(“0”)){
发送通知(“滴度试验1111”、“身体试验1111”);
}else if(响应等于(“1”)){
发送通知(“滴度试验2222”、“身体试验2222”);
}否则{
发送通知(“滴度试验3333”、“身体试验3333”);
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(MyService.this,error.toString(),Toast.LENGTH_SHORT.show();
d(“截击日志”,“错误:+Error.getMessage());
}
});
//将请求添加到请求队列
int-socketTimeout=30000;//30秒-更改为您想要的
RetryPolicy policy=新的DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(streq,标记字符串请求);
//每5秒设置一次定期报警
}
私有void sendNotification(字符串标题、字符串消息体){
长[]模式={500500};
Uri alarmSound=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_通知);
NotificationCompat.Builder notificationBuilder=新建NotificationCompat.Builder(此)
.setSmallIcon(R.mipmap.ic_启动器)
.setContentTitle(标题)
.setContentText(messageBody)
.setAutoCancel(真)
.setSound(警报声)
.设置灯(颜色:蓝色,500500)
.设置振动(模式);
通知经理通知经理=
(NotificationManager)getSystemService(上下文通知服务);
如果(通知ID>1073741824){
通知_ID=0;
}
notificationManager.notify(NOTIFICATION_ID++,notificationBuilder.build());
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gih.testmass">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<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=".broadtest"
android:process=":remote">
</receiver>
<service
android:name=".MyService"
android:exported="false">
</service>
</application>
<?xml version="1.0" encoding="utf-8"?>
您需要将该服务作为前台服务启动。当您从最近清除应用程序时,它将终止服务
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_notification)
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.mipmap.ic_launcher))
.setContentTitle("WhatsApp Reminder Service.")
.setContentText("Touch to configure.");
Intent startIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 965778, startIntent, 0);
builder.setContentIntent(pendingIntent);
startForeground(965778, builder.build());
return START_REDELIVER_INTENT;
}
在使用前台服务时,有必要生成通知。
希望能有帮助
我知道你使用了IntentService
见这个问题的答案
当用户与您的应用程序没有特别交互时,在设备上运行进程
这些步骤将涉及:
1.更新android清单xml
2.设置广播接收器收听相关事件
3.在应用程序未运行时为上下文设置后台服务
Android menifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gih.testmass">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<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=".broadtest"
android:process=":remote">
</receiver>
<service
android:name=".MyService"
android:exported="false">
</service>
</application>
<?xml version="1.0" encoding="utf-8"?>
这里的com.example.app.PERIODIC_TASK_HEART_BEAT
是应用程序自己的广播,通过我们的restartPeriodicTaskHeartBeat
方法创建和发送
您的Alarmmanager
应该有这一行
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
现在,您的后台服务类:
public class BackgroundService extends Service {
private static final String TAG = "BackgroundService";
PeriodicTaskReceiver mPeriodicTaskReceiver = new PeriodicTaskReceiver();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MyApplication myApplication = (MyApplication) getApplicationContext();
SharedPreferences sharedPreferences = myApplication.getSharedPreferences();
IntentFilter batteryStatusIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatusIntent = registerReceiver(null, batteryStatusIntentFilter);
if (batteryStatusIntent != null) {
int level = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPercentage = level / (float) scale;
float lowBatteryPercentageLevel = 0.14f;
try {
int lowBatteryLevel = Resources.getSystem().getInteger(Resources.getSystem().getIdentifier("config_lowBatteryWarningLevel", "integer", "android"));
lowBatteryPercentageLevel = lowBatteryLevel / (float) scale;
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Missing low battery threshold resource");
}
sharedPreferences.edit().putBoolean(Constants.BACKGROUND_SERVICE_BATTERY_CONTROL, batteryPercentage >= lowBatteryPercentageLevel).apply();
} else {
sharedPreferences.edit().putBoolean(Constants.BACKGROUND_SERVICE_BATTERY_CONTROL, true).apply();
}
mPeriodicTaskReceiver.restartPeriodicTaskHeartBeat(BackgroundService.this);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
startSelf();
}
}
在这里,Backgroundservice试图找到设备的低电池阈值,并在尝试重新启动广播接收器之前适当设置电池控制标志
而START\u STICKY
将在服务被终止后尝试重新创建服务,并再次调用onStartCommand()
,意图为空
最后,为您的应用程序类启动后台服务:
public class MyApplication extends Application {
private static final String TAG = "MyApplication";
@Override
public void onCreate() {
super.onCreate();
// Initialize the singletons so their instances
// are bound to the application process.
...
Intent startServiceIntent = new Intent(context, BackgroundService.class);
startService(startServiceIntent);
}
}
有关详细实施信息,请参见:
确保在您的Mainifest中提供这样的服务
<service
android:name=".service.youservice"
android:exported="true"
android:process=":ServiceProcess" />
然后,您的服务将在另一个名为ServiceProcess的进程上运行
如果您想让您的服务永不磨灭:
onStartCommand()返回START\u
onDestroy()->调用startself
如果没有任何效果,请使用服务。您的Android清单在哪里?对不起。。。我现在就写,为什么在另一个流程中使用接收器/服务?权限是否处于活动状态?我不知道权限。。我在这里搜索后使用了它谢谢,我理解你的代码除了后台服务的代码,她做什么?我做了你说的每一件事,但在我从最近的应用程序中删除后,我没有收到任何东西server@AhmedShaheen您是这样启动服务的吗:activity startService的onCreate()(newintent(getBaseContext()),BackServices.class));还可以在另一个进程中运行服务…i