廣播中alertDialog彈窗的顯示以及隱藏

- 廣播的使用:

第一步:定義一個廣播接收者(BroadcastReceiver)

 public class CancelBroadcast extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
           //將其設爲true
          CancelCall.cancel="true";

}

}

第二步:在manifest裏面註冊該廣播

<receiver android:name=".CancelBroadcast" >
        <intent-filter>
            <action android:name="com.cravechina.iot.crave.CANCEL" />
        </intent-filter>
    </receiver>

第三步:觸發廣播的響應

    if(message.Message.equals("cancelCall")){
        Intent intent1=new Intent("com.cravechina.iot.crave.CANCEL");
        sendBroadcast(intent1);
        String i=CancelCall.cancel;
        System.out.println(i);
    }

以上就是廣播的基本使用,下面進入正題

在廣播中alertDialog彈窗以及調用系統鈴聲的實現:

public class VideoChatBroadcast extends BroadcastReceiver{
private MediaPlayer mediaPlayer;
AlertDialog alertDialog;
@Override
public void onReceive(final Context context, Intent intent) {
    //進來要將這個值設爲false
    CancelCall.cancel="false";
    Bundle bundle = intent.getExtras();   
    final String url=bundle.getString("msg");
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);

    //調用鈴聲
    mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(context, RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        mediaPlayer.setLooping(true); //設置循環
        mediaPlayer.prepare();
        mediaPlayer.start();

    } catch (Exception e) {
        e.printStackTrace();
    }


    dialogBuilder.setTitle("提示");
    dialogBuilder.setMessage("有人來電");  
    dialogBuilder.setCancelable(false);  

    dialogBuilder.setPositiveButton("接聽", new DialogInterface.OnClickListener() {  
        @Override  
        public void onClick(DialogInterface dialog, int which) { 
            Intent intent=new Intent(context,VideoChat2Activity.class);
            intent.putExtra("msg", url);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
            context.startActivity(intent);
            mediaPlayer.stop();
            mediaPlayer.release();

        }  
    }); 
    dialogBuilder.setNegativeButton("拒絕", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            mediaPlayer.stop();
            mediaPlayer.release();
            dialog.dismiss();
            //拒絕接聽還需要發送消息給手機端,告知拒絕 了
            cancelMessage(context);
        }
    });
    alertDialog = dialogBuilder.create();  
    // 需要設置AlertDialog的類型,保證在廣播接收器中可以正常彈出  
    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);  
    alertDialog.show();

    //計時器
    mHandler.postDelayed(mRunnable, 1000);

}

private void cancelMessage(final Context context) {
    //拿到自己的token
    SharedPreferences sp=context.getSharedPreferences("config", context.MODE_PRIVATE);
    String token=sp.getString("token", null);
    //拿到設備的token
    SharedPreferences sp2=context.getSharedPreferences("deviceData", context.MODE_PRIVATE);
    String deviceToken=sp2.getString("deviceToken", null);
    //設備token集合
    ArrayList<String>tokenList=new ArrayList<String>();
    tokenList.add(deviceToken);
    //拿到取消的消息
    String msg="cancelCall";
    //base64編碼
    msg=Base64.encodeToString(msg.getBytes(),Base64.DEFAULT);
    RequestParams params=new RequestParams();
    //添加請求頭
    params.setHeader("X-Client-Token", token);
    params.setHeader("Content-Type", "application/json");
    params.setHeader("Cache-Control", "no-cache");

    Map<String, Object> map =new HashMap<String, Object>();
    map.put("msg", msg);
    map.put("flag", 2);
    map.put("callback", 1);
    map.put("access_tokens", tokenList);
    //轉換成json
    Gson gson=new Gson();
    String result=gson.toJson(map);
    try {
        params.setBodyEntity(new StringEntity(result));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //              gson.toJson(map, Map.class);
    HttpUtils utils=new HttpUtils();
    utils.send(HttpMethod.POST, GlobalUrl.CANCEL_CALL_URL, params,new RequestCallBack<String>() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            Toast.makeText(context, "發送失敗", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onSuccess(ResponseInfo<String> arg0) {
            Toast.makeText(context, "發送失敗", Toast.LENGTH_SHORT).show();

// UIUtils.showToast(VideoChatActivity.this, “發送成功”);

        }
    });
}

//  }
String cancel;
Handler mHandler=new Handler();
Runnable mRunnable=new Runnable() {

    @Override
    public void run() {
        mHandler.postDelayed(mRunnable, 1000);
        cancel=CancelCall.cancel;
        System.out.println("cancel1:"+cancel);
        if(cancel.equals("true")){
            if(mediaPlayer.isPlaying()){
                mediaPlayer.stop();
                mediaPlayer.release();
            }
            alertDialog.dismiss();
            //停止handler
            mHandler.removeCallbacks(mRunnable);
        }
    }
};

}

以上代碼是廣播接收者中的彈窗的實現以及隱藏;同樣的,這個廣播也需要註冊與觸發。

註冊:

<!-- 註冊廣播 -->
<receiver android:name="com.cravechina.iot.cravehome.broadcast.VideoChatBroadcast" >
        <intent-filter>
            <action android:name="com.cravechina.iot.crave.VIDEOCHAT" />
        </intent-filter>
    </receiver>

觸發:

Intent intent = new Intent("com.cravechina.iot.crave.VIDEOCHAT");  
Bundle bundle = new Bundle();
bundle.putString("msg",message.Message);//這裏可以傳送數據
intent.putExtras(bundle); 
sendBroadcast(intent);  

以上就是彈窗的顯示與隱藏。
這時候項目還有一個需求,彈窗需要在接到某個消息的情況下自動隱藏,也就是類似電話被掛斷時的效果:

我的做法就是定義一個全局變量,在做一個廣播,當接收到消息變化的時候,廣播就發送這個全局變量發生了改變,然後在彈窗的廣播裏面寫一個計時器一直在取這個全局變量,當發現發生了變化則彈窗消失。

下面是代碼:
定義的全局變量:

public class CancelCall {
    public static String cancel="false";
}

廣播就是上面的兩個,第一個是廣播全局變量的變化,第二個就是計時器獲取變量之後絕對彈窗的狀態
當第一個廣播收到消息的時候,將這個全局變量的值改變,然後第二個播通過計時器獲取的值也改變了,彈窗的轉檯就發送了改變。

計時器獲取全局變量:

String cancel;
Handler mHandler=new Handler();
Runnable mRunnable=new Runnable() {

    @Override
    public void run() {
        mHandler.postDelayed(mRunnable, 1000);
        cancel=CancelCall.cancel;
        System.out.println("cancel1:"+cancel);
        if(cancel.equals("true")){
            if(mediaPlayer.isPlaying()){
                mediaPlayer.stop();
                mediaPlayer.release();
            }
            alertDialog.dismiss();
            //停止handler
            mHandler.removeCallbacks(mRunnable);
        }
    }
};
發佈了23 篇原創文章 · 獲贊 8 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章