2013年2月7日 星期四

[Android]Service Dialog製作

可行性Survey:
Android: Service中创建窗口Dialog

Mo菲思 - Service 建立 Dialog對話框

Service 建立 Dialog對話框

紅黑聯盟 - android在Service中弹出Dialog对话框,即全局性对话框


先不說是什麼需求導致要這樣作
但是Survey了一下文件 都說service是沒有界面的
那硬是要在Service裡面呼叫dialog不行的話 alertdialog 可以嗎
因為alertdialog繼承了dialog
 但因為有這樣的需求 硬著頭皮試試看了
在實作之前Survey一下正確註冊service的方式:
LP學CService 建立 Dialog對話框++ - 【Android】Service 注册时的注意点

[Android 界面] 为什么service能弹出alertdialog 却不能弹出dialog

沒錯就是衝著這篇說可以 我怎樣都想試試看,衝了!!

主程式:MainActivity.java

package com.example.a2service;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
private Button start;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)this.findViewById(R.id.start);
start.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
call();
}
private void call() {
String seat_id = "3345678";
Intent intent = new Intent();
//放入要傳送的訊息在intent內
intent.putExtra("seat_id", seat_id);
//設定intent發送及目的class
intent.setClass(MainActivity.this,service.class);
//用intent啟動service
     startService(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

副程式:service.java

public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
//取得傳來的intent內的值並存放在seat變數中
        String seat = intent.getExtras().getString("seat_id");
        showdialog();
}
private void showdialog() {
//設定alertdialog並啟動
View v = View.inflate(this, R.layout.dialog, null);
    AlertDialog.Builder b = new AlertDialog.Builder(this);
    final AlertDialog d = b.create();
    d.setTitle(seat+"您好!");
    DialogInterface.OnClickListener OkClick = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        d.dismiss();
        }
    };
    d.setButton("OK", OkClick);
    d.setView(v);
//加入這行alertdialog才會正常顯示,否則程序會崩潰
    d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);  
    d.show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

Android Service中弹出全局对话框中提到:
//d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); //窗口可以获得焦点,响应操作
//d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY); //窗口不可以获得焦点,点击时响应窗口后面的界面点击事件
第一個就是我這隻副程式後面加上的
第二個後面的背景依然可以操作 但是彈出的alertdialog的按鈕就不能用了

第三個d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); //系统中关机对话框就是这个属性
加入了程序會崩潰,所以我沒加上

最後記得在Manifest註冊
uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"
service android:name=".service"

就可以用service彈出alertdialog了!!!大成功!!!

沒有留言:

張貼留言