如何在后台发送通知?

How to send notification in background?

我使用 IntentService 从数据库中获取数据。这是我的代码:

GetDataService.java

public class GetDataService extends IntentService {

    public GetDataService() {
        super("GetDataService");

    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Parameter parameter = new Parameter();
        String data = (new LandSlideHttpClient()).getDeviceData();

        try {
            parameter = JSONLandslideParser.getParameter(data);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Intent in = new Intent();
        in.setAction(DataReceiver.ACTION_RESP);
        in.addCategory(Intent.CATEGORY_DEFAULT);
        in.putExtra("123", (Parcelable) parameter);
        sendBroadcast(in);

        long ct = System.currentTimeMillis();
        AlarmManager mgr = (AlarmManager) getApplicationContext()
                .getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(getApplicationContext(), GetDataService.class);
        PendingIntent pendingIntent = PendingIntent.getService(
                getApplicationContext(), 0, i, 0);

        mgr.set(AlarmManager.RTC_WAKEUP, ct + 10000, pendingIntent);
        stopSelf();
    }
}

CurrentData.java

public class CurrentDataService extends Fragment {

public CurrentDataService() {
    super();
}

private DataReceiver dataReceiver;

TextView id;
TextView temp;
TextView acc;
TextView moisture;
TextView battery;
TextView date;
TextView time;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.currentdata_layout,
            container, false);
    id = (TextView) rootView.findViewById(R.id.showID);
    temp = (TextView) rootView.findViewById(R.id.showTEMP);
    acc = (TextView) rootView.findViewById(R.id.showACC);
    moisture = (TextView) rootView.findViewById(R.id.showMoisture);
    battery = (TextView) rootView.findViewById(R.id.showBat);
    date = (TextView) rootView.findViewById(R.id.showDATE);
    time = (TextView) rootView.findViewById(R.id.showTIME);

    return rootView;
}

@Override
public void onResume() {
    IntentFilter filter = new IntentFilter(DataReceiver.ACTION_RESP);
    filter.addCategory(Intent.CATEGORY_DEFAULT);

    dataReceiver = new DataReceiver();
    getActivity().registerReceiver(dataReceiver, filter);

    Intent intent = new Intent(getActivity(), GetDataService.class);
    getActivity().startService(intent);
    super.onResume();
}

@Override
public void onDestroy() {
    getActivity().unregisterReceiver(dataReceiver);
    super.onDestroy();
}

public class DataReceiver extends BroadcastReceiver {

    public static final String ACTION_RESP = "getdatafromBroadcast";

    @Override
    public void onReceive(Context context, Intent intent) {
        Parameter result = (Parameter) intent.getParcelableExtra("123");

        id.setText(result.getId());
        temp.setText(" " + result.getTemp());// + "  °C");
        acc.setText(" " + result.getAcc());// + "  m/s2");
        moisture.setText(" " + result.getMoisture());// +// "  mps");
        battery.setText(" " + result.getBattery());// + "  %");
        date.setText(result.getDate());
        time.setText(result.getTime());
        if (Float.parseFloat(temp.getText().toString()) > 25) {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    getActivity()).setContentTitle("My notification")
                    .setContentText("Danger")
                    .setWhen(System.currentTimeMillis());

            NotificationManager mNotificationManager = (NotificationManager) getActivity()
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(1, mBuilder.build());
        }
    }

}
}

我有两个问题:

  1. 我想要当 temp 的值大于 25 时,然后创建一个通知通知用户以防应用程序关闭。但是我的代码没有创建通知。

  2. 我使用导航栏并有一个名为 Current data 的第二个选项卡,它显示当前信息。我使用 intentservice 和警报管理器,但我的 CurrentTab 仅在我的应用程序显示此选项卡时运行,但如果我移动到另一个选项卡,CurrentTab 不显示 Toast(我设置 Toast show when temp > 25)。那么,我的 intentservice 是不是错了?

    如果你知道我的问题,请帮助我。

首先检查你的if条件是否有效..敬酒或打印一些东西.. 如果有效,请将此代码放入其中:

 NotificationManager mManager;    
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);

 //Put the name of the class where you want to go on clicking the notification.. I used MainActivity

       Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

       Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());

       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

       PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_ONE_SHOT);
       notification.flags |= Notification.FLAG_AUTO_CANCEL;
       notification.setLatestEventInfo(this.getApplicationContext(), "Notification", "This is a test message!", pendingNotificationIntent);

       mManager.notify(0, notification);

此通知代码将起作用,只要确保您的 if 条件起作用