如何在后台发送通知?

时间:2015-04-24 07:37:36

标签: java android android-intent notifications intentservice

我使用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和Alarm manager,但我的CurrentTab只在我的应用显示此标签时运行,但如果我移动到另一个标签,CurrentTab不显示Toast(我设置Toast show temp&gt ; 25)。那么,我的意图服务是错的吗?

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

1 个答案:

答案 0 :(得分:0)

首先检查你的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条件正常工作