全速加载中

Android开发学习笔记-关于Android的消息推送以及前后台切换

下面是最简单的Android的消息推送的实现方法

package com.example.shownotic;

import java.util.Random;

import android.support.v7.app.ActionBarActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore.Audio.Media;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    private static final int STATUS_BAR_ID = 0;
    Button btnShowNotic = null;
    private Random random = new Random(20);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnShowNotic = (Button) findViewById(R.id.btnShowNotic);
        btnShowNotic.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new Thread(new Runnable() {
                    public void run() {
                        while(true)
                        {
                            SystemClock.sleep(30000);
                            showNotic();
                        }
                    }
                }).start();
                showNotic();
            }

            
        });
    }
    private void showNotic() {
        NotificationManager notificationManger = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        CharSequence tickerText = "Gigade";
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon , tickerText , when );
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        
        CharSequence contentText = "show:"+random.nextInt(30);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_WEB_SEARCH);
        intent.setData(Uri.parse("http://www.baidu.com"));
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent , 0);
        notification.setLatestEventInfo(this, getTitle(), contentText , contentIntent );
        
        notificationManger.notify(0, notification );
        
    }
    
}

 

posted @ 2014-09-16 18:17  许鸿飞  阅读(3442)  评论(0编辑  收藏  举报