在Service中弹出Notification
我的Service类:
- Java code
package test.service;import test.activity.TestServiceActivity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.IBinder;public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); String ns = Context.NOTIFICATION_SERVICE; NotificationManager nm = (NotificationManager) getSystemService(ns); CharSequence tickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(1, tickerText, when); PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, TestServiceActivity.class), 0); notification.setLatestEventInfo(this, "出勤提醒", "有15分就到上班", pi); nm.notify(1, notification); }}
我的TestServiceActivity类:
- Java code
package test.activity;import test.service.MyService;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;public class TestServiceActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void start(View view) { Intent serviceIntent = new Intent(this, MyService.class); // serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startService(serviceIntent); } public void stop(View view) { Intent serviceIntent = new Intent(this, MyService.class); // serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); stopService(serviceIntent); }}
mian.xml
- XML code
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="start" android:text="start service" android:textSize="20dip" /> <Button android:id="@+id/stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="stop" android:text="stop service" android:textSize="20dip" /></LinearLayout>
当我跑起项目,点击start service按钮,去触发onStart方法的时候,就报错了:
bad notification posted from package
请问是我的代码有问题吗?
其实我想做一个定时提醒用户上班的功能,想通过开机启动一个服务,然后通过AlarmManager去定时判断,到了设定的时间就弹出Notification提醒用户上班,我这样的思路有问题吗?
分数不多,请多过来帮帮忙,困扰了好几天了!
------解决方案--------------------
Service无法弹出Notification,你可以在Service里发送个广播,在broadcast里接收广播并弹出Notification