android运行服务自动启动应用程序
在我的应用程序中,我启动一项服务,在应用程序处于后台时接收通知-此服务强制我的应用程序在我停止后自动启动。我试图通过使用挂起的意图来解决这个问题,但它仍然发生 以下是我启动服务的意图:android运行服务自动启动应用程序,android,service,push-notification,android-pendingintent,Android,Service,Push Notification,Android Pendingintent,在我的应用程序中,我启动一项服务,在应用程序处于后台时接收通知-此服务强制我的应用程序在我停止后自动启动。我试图通过使用挂起的意图来解决这个问题,但它仍然发生 以下是我启动服务的意图: Intent messageReceivingIntent = new Intent(this, MessageReceivingService.class); messageReceivingIntent.putExtra("myUserId", myUserId); Pending Inten message
Intent messageReceivingIntent = new Intent(this, MessageReceivingService.class);
messageReceivingIntent.putExtra("myUserId", myUserId);
Pending Inten messagePendingIntent = PendingIntent.getService(this, 0, messageReceivingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
// Perform the operation associated with our pendingIntent
messagePendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
若我通过externalreceiver调用服务,我会得到一个nullpointerexception。知道为什么吗
这是我的广播接收机呼叫:
messageReceivingIntent = new Intent(this, MessageReceivingService.class);
messageReceivingIntent.putExtra("myUserId", myUserId);
messageReceivingIntent.setAction("com.example.androidtest");
sendBroadcast(messageReceivingIntent);
这是我的广播接收器:
public class ExternalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent!=null){
Bundle extras = intent.getExtras();
if(!MapsActivity.inBackground){
MessageReceivingService.sendToApp(extras, context);
}
else{
MessageReceivingService.saveToLog(extras, context);
}
}
}
}
这是MessageReceivingService
public class MessageReceivingService extends Service {
private GoogleCloudMessaging gcm;
public static SharedPreferences savedValues;
public static final String INSTANCE_ID_SCOPE = "GCM";
final String BASE_URL = "http://www.example.com/";
public String myUserId;
public String registeredUserId;
public String token;
static PendingIntent pendingIntent;
public static void sendToApp(Bundle extras, Context context) {
Intent newIntent = new Intent();
newIntent.setClass(context, MapsActivity.class);
newIntent.putExtras(extras);
ShortcutBadger.applyCount(Content.getAppContext(), 0);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
}
public void onCreate() {
super.onCreate();
final String preferences = getString(R.string.preferences);
savedValues = getSharedPreferences(preferences, Context.MODE_PRIVATE);
// In later versions multi_process is no longer the default
if (VERSION.SDK_INT > 9) {
savedValues = getSharedPreferences(preferences, Context.MODE_MULTI_PROCESS);
}
gcm = GoogleCloudMessaging.getInstance(getBaseContext());
// Let AndroidMobilePushApp know we have just initialized and there may be stored messages
sendToApp(new Bundle(), this);
}
protected static void saveToLog(Bundle extras, Context context) {
SharedPreferences.Editor editor = savedValues.edit();
String numOfMissedMessages = context.getString(R.string.num_of_missed_messages);
int linesOfMessageCount = 0;
for (String key : extras.keySet()) {
String line = String.format("%s=%s", key, extras.getString(key));
editor.putString(key, line);
linesOfMessageCount++;
}
editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
editor.putInt(numOfMissedMessages, savedValues.getInt(numOfMissedMessages, 0) + 1);
editor.commit();
String type = extras.getString("model");
String id = extras.getString("id");
String userId = extras.getString("user_id");
//postNotification(new Intent(context, MapsActivity.class), context);
if(type != null) {
if (type.equals("content")) {
Intent contentIntent = new Intent(context, ContentDetailActivity.class);
Log.v("userID", userId);
contentIntent.putExtra("contentId", id);
if (userId != null) {
contentIntent.putExtra("userId", userId);
}
postNotification(contentIntent, context);
} else if (type.equals("user")) {
Intent userIntent = new Intent(context, ProfileActivity.class);
userIntent.putExtra("userId", id);
postNotification(userIntent, context);
}
} else {
postNotification(new Intent(context, NotificationsActivity.class), context);
}
ShortcutBadger.applyCount(Content.getAppContext(), Integer.valueOf(savedValues.getInt(Content.getAppContext().getString(R.string.num_of_missed_messages), 0)));
}
protected static void postNotification(Intent intentAction, Context context) {
final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
pendingIntent = PendingIntent.getActivity(context, 0, intentAction, PendingIntent.FLAG_UPDATE_CURRENT);
int numOfMissedMessages = 0;
String missedMessage = "";
if(savedValues != null){
missedMessage = savedValues.getString("message", "nothing there");
}
Log.v("NUMOFMISSEDMESSAGES", String.valueOf(numOfMissedMessages));
final Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(missedMessage.substring(missedMessage.indexOf("=") + 1, missedMessage.length()))
.setContentText("")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
mNotificationManager.notify(R.string.notification_number, notification);
}
private void register() {
new AsyncTask() {
protected Object doInBackground(final Object... params) {
try {
String instanceId = InstanceID.getInstance(getApplicationContext()).getId();
//token = gcm.register(getString(R.string.project_number));
token = InstanceID.getInstance(getApplicationContext()).getToken(getString(R.string.project_number), INSTANCE_ID_SCOPE);
Log.i("registrationId", token);
} catch (IOException e) {
Log.i("Registration Error", e.getMessage());
}
return true;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
new SendRegUserId().execute();
}
}.execute();
}
public IBinder onBind(Intent arg0) {
return null;
}
}
使用接收通知,然后将其发送到您的。这将允许您向用户发送通知
,而无需启动应用程序
==========编辑1: 因此,您的广播接收器需要启动服务,而不是调用其方法。因此,在检查意图是否为空后,应遵循以下几点:
ComponentName comp = new ComponentName(context.getPackageName(), YourIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp));
setResultCode(Activity.RESULT_OK);
此外,如果您在手机关机后仍希望接收通知,则您的广播接收器应延长
此外,您的服务
也应该是一个。我认为Android Studio实际上附带了一些预先制作的GCM类或GCM应用程序,可以解决90%的这些小问题。这是一个更好的起点
请查看以获取更多帮助 使用接收通知,然后将其发送给您的用户。这将允许您向用户发送通知
,而无需启动应用程序
==========
编辑1:
因此,您的广播接收器需要启动服务,而不是调用其方法。因此,在检查意图是否为空后,应遵循以下几点:
ComponentName comp = new ComponentName(context.getPackageName(), YourIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp));
setResultCode(Activity.RESULT_OK);
此外,如果您在手机关机后仍希望接收通知,则您的广播接收器应延长
此外,您的服务
也应该是一个。我认为Android Studio实际上附带了一些预先制作的GCM类或GCM应用程序,可以解决90%的这些小问题。这是一个更好的起点
请查看以获取更多帮助 一些可能的解决方案-
1) 使用广播接收机
2) 使用onPause()和onResume()方法
3) 或者,根据我的说法,最好是实现Firebase云消息通知
看看这个
它大大减少了电池和服务器的工作量。这是谷歌推出的一项全新服务
或者,我认为您的服务代码中可能存在缺陷一些可能的解决方案-
1) 使用广播接收机
2) 使用onPause()和onResume()方法
3) 或者,根据我的说法,最好是实现Firebase云消息通知
看看这个
它大大减少了电池和服务器的工作量。这是谷歌推出的一项全新服务
或者我认为您的服务代码中可能存在错误您是否使用了广播接收器
?您在服务中使用了大量静态变量。这可能是你的麻烦的原因。如果您收到NullPointerException
请发布错误消息,包括来自logcat的stacktrace,并解释当时发生的情况。另外,从您的服务的onStartCommand()
发布代码。您使用的是广播接收器吗?您的服务中使用了大量静态变量。这可能是你的麻烦的原因。如果您收到NullPointerException
请发布错误消息,包括来自logcat的stacktrace,并解释当时发生的情况。另外,从您的服务的onStartCommand()
中发布代码。我与gcm斗争了很长一段时间,遇到了一些问题。我很想修复给定的代码,因为除了自启动问题外,它工作得很好。我非常绝望,检查并考虑把你的用例整合到那个样本中,它已经准备就绪,这将为你省去很多麻烦。GCM总是在变化(现在是Firebase),我不得不在每次迭代中手动更新代码,这不是我推荐的方式。我已经与GCM斗争了很长时间,并且遇到了问题。我很想修复给定的代码,因为除了自启动问题外,它工作得很好。我非常绝望,检查并考虑把你的用例整合到那个样本中,它已经准备就绪,这将为你省去很多麻烦。GCM总是在变化(现在是Firebase),我不得不在每次迭代中手动更新代码,这不是我推荐的方法