Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在后台发送通知?_Java_Android_Android Intent_Notifications_Intentservice - Fatal编程技术网

Java 如何在后台发送通知?

Java 如何在后台发送通知?,java,android,android-intent,notifications,intentservice,Java,Android,Android Intent,Notifications,Intentservice,我使用IntentService从数据库中获取数据。这是我的代码: GetDataService.java public class GetDataService extends IntentService { public GetDataService() { super("GetDataService"); } @Override protected void onHandleIntent(Intent intent)

我使用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();
    }
}
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());
        }
    }

}
}
CurrentData.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();
    }
}
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());
        }
    }

}
}
我有两个问题:

  • 我希望当
    temp
    的值大于
    25
    时,创建一个通知,在应用程序关闭时通知用户。但我的代码不会创建通知

  • 我使用导航栏,还有第二个选项卡,名为
    当前数据
    ,显示当前信息。我使用intentservice and Alarm manager,但我的
    CurrentTab
    仅在我的应用程序显示此选项卡时运行,但如果我移动到另一个选项卡,
    CurrentTab
    不显示Toast(我设置Toast show when
    temp
    25
    )。那么,我的意向服务错了吗

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


  • 首先检查你的状况是否正常。。放一个烤面包或打印一些东西。。 如果有效,请将此代码放入其中:

     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(Float.compare(result.getTemp(),25f)>=0)
    我经常在谷歌上搜索,但我还没有找到答案,所以我发布了这篇文章。你知道我的问题吗?@Backbelt你是什么意思?谢谢你@prakar,你的代码正在工作,但它不会自动删除。