Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/193.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 Notifications - Fatal编程技术网

Java 在应用程序未运行时创建通知

Java 在应用程序未运行时创建通知,java,android,android-notifications,Java,Android,Android Notifications,在我正在使用的这个应用程序上,我希望在应用程序不在前台时收到通知。基本上,当你在应用程序中时,你的在线用户可以向你发送消息。根据您在应用程序中的位置,您将获得一个对话框,说明您收到了一条消息或在消息活动中获得了全文。但是,我想处理您在不运行应用程序时收到的消息。我已经建立了一个通知活动,但我不知道如何让应用程序在后台运行并推送通知 public class CreateNotification extends Activity { View viewer; @Override

在我正在使用的这个应用程序上,我希望在应用程序不在前台时收到通知。基本上,当你在应用程序中时,你的在线用户可以向你发送消息。根据您在应用程序中的位置,您将获得一个对话框,说明您收到了一条消息或在消息活动中获得了全文。但是,我想处理您在不运行应用程序时收到的消息。我已经建立了一个通知活动,但我不知道如何让应用程序在后台运行并推送通知

public class CreateNotification extends Activity {
    View viewer;
     @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_notification);
        Intent intent = new Intent(this, ReceiveNotification.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // Build notification
        // Actions are just fake
        Notification noti = new Notification.Builder(this)
            .setContentTitle("Received a message")
            .setContentText("Subject").setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .addAction(R.drawable.ic_launcher, "Rply", pIntent)
            .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Hide the notification after its selected
        noti.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0, noti);
      }

    } 
下面是一个活动示例,该活动将收到一条消息发送给您的警报

public class TabExercise extends TabActivity implements ChatCallbackAdapter{
    /** Called when the activity is first created. */
    public StartSocket connect;
    public static Context mContext;
    private ConnectSocket connectsocket;
    final Context context = this;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_exercise);

        TabHost tabHost = getTabHost();
        connectsocket= new ConnectSocket(this);
        connectsocket.start();
       // connect=new StartSocket();
        mContext=TabExercise.this;
        // Tab for Contacts
        TabSpec contacts = tabHost.newTabSpec("Contacts");
        // setting Title and Icon for the Tab
        contacts.setIndicator("Contacts", getResources().getDrawable(R.drawable.ic_launcher));
        Intent contactsIntent = new Intent(this, Contacts.class);
        contacts.setContent(contactsIntent);

        // Tab for Songs
        TabSpec songspec = tabHost.newTabSpec("Notifications");        
        songspec.setIndicator("Notifications", getResources().getDrawable(R.drawable.ic_launcher));
        Intent songsIntent = new Intent(this, Notifications.class);
        songspec.setContent(songsIntent);

        // Tab for Videos
        TabSpec videospec = tabHost.newTabSpec("Messages");
        videospec.setIndicator("Messages", getResources().getDrawable(R.drawable.ic_launcher));
        Intent videosIntent = new Intent(this, MyMessages.class);
        videospec.setContent(videosIntent);

        // Adding all TabSpec to TabHost
        tabHost.addTab(contacts); // Adding photos tab
        tabHost.addTab(songspec); // Adding songs tab
        tabHost.addTab(videospec); // Adding videos tab

        TabWidget widget = tabHost.getTabWidget();
        for(int i = 0; i < widget.getChildCount(); i++) {
            View v = widget.getChildAt(i);

            // Look for the title view to ensure this is an indicator and not a divider.
            TextView tv = (TextView)v.findViewById(android.R.id.title);
            if(tv == null) {
                continue;

            }
            v.setBackgroundResource(R.layout.tab_indicator_holo);
        }
        Intent in= getIntent();
        String tabSel=in.getStringExtra("tab_index");
        //Bundle extras = in.getExtras();
        if (tabSel != null) {

            if(tabSel.equals("1")){
                tabHost.setCurrentTab(Integer.valueOf(tabSel)); 
            }
            if(tabSel.equals("2")){
                tabHost.setCurrentTab(Integer.valueOf(tabSel)); 
            }
        }
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
    //  SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
     //   SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); 
        // Assumes current activity is the searchable activity
     //   searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        //searchView.setInputType(InputType.TYPE_CLASS_TEXT);
     //   searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.logout:
                // app icon in action bar clicked; go home
                SaveSharedPreference.setUserName(TabExercise.this,"");
                SaveSharedPreference.setName(TabExercise.this,"");
                SaveSharedPreference.setUserId(TabExercise.this,"");
                Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;

            case R.id.find_a_user:
                // app icon in action bar clicked; go home

                Intent in = new Intent(this, Contacts.class);

                startActivity(in);
                return true;

            case R.id.editprofile:

                Intent inte=new Intent(this, EditProfile.class);
                startActivity(inte);
                return true;
            case R.id.chat:
                Intent inti = new Intent(this, StartChat.class);
                startActivity(inti);
                return true;

            case R.id.delete_all:
                //connect.start();
                Intent inten=new Intent(TabExercise.this, CreateNotification.class);
                startActivity(inten);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void callback(JSONArray data) throws JSONException {
        // TODO Auto-generated method stub

    }
    @Override
    public void on(String event, JSONObject data) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onMessage(String message) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onMessage(JSONObject json) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onConnect() {
        // TODO Auto-generated method stub

    }
    @Override
    public void onDisconnect() {
        // TODO Auto-generated method stub

    }
    @Override
    public void onConnectFailure() {
        // TODO Auto-generated method stub

    }
    @Override
    public void onMessageReceived(Message m) {
        // TODO Auto-generated method stub
        Log.d("Status","This is the status "+m.status);
        if(m.status.equals("ready")){
            connectsocket.login(SaveSharedPreference.getName(TabExercise.this), SaveSharedPreference.getUserId(TabExercise.this));
            connectsocket.subscribe();
        }
        if(m.status.equals("call")){
            Intent intent=new Intent(TabExercise.this, StartCall.class);
            startActivity(intent);
        }
        if(m.status.equals("message")){
            System.out.println("Received a message "+m.msg+" and a name "+m.name);
            final String name=m.name;
            final String pid=m.pid;
            final String msg=m.msg;

            //Intent intenter=new Intent(TabExercise.this, CreateNotification.class);
            //startActivity(intenter);

            runOnUiThread(new Runnable(){

            public void run(){
             AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);
             alertDialogBuilder.setTitle(name+" just sent you a message");
             alertDialogBuilder.setMessage("Click yes to go to the message");
             alertDialogBuilder

                .setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        Intent inte=new Intent(TabExercise.this, Chat.class);
                        Bundle extras=new Bundle();
                        extras.putString("name", name);
                        extras.putString("pid", pid);
                        extras.putString("msg", msg);
                        inte.putExtras(extras);
                        startActivity(inte);

                        dialog.cancel();
                    }
                  })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            }
            });
        }
    }

使用报警管理器定期触发报警。当收到警报时,运行后台服务以轮询服务器是否收到任何消息


或者,如果您希望服务器将消息直接推送到您的设备,您可以使用谷歌云消息。

ahhh有趣的是,让我来看看。