0

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

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

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

这是创建通知的通知活动。

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);
      }

    } 
4

1 回答 1

0

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

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

于 2013-07-25T02:38:11.670 回答