程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> service-請問廣播接受者不能發送廣播嗎?還是我寫的代碼有問題啊?

service-請問廣播接受者不能發送廣播嗎?還是我寫的代碼有問題啊?

編輯:編程解疑
請問廣播接受者不能發送廣播嗎?還是我寫的代碼有問題啊?

public class netReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Intent wifi = new Intent();
    if(isWifi(context)){
        wifi = new Intent(context, MyService.class);
        context.startService(intent);
    }else{
        wifi.setAction("net.s5c.Changelink.wifiOff");
        sendBroadcast(wifi);
    }

    Toast.makeText(context, "監聽到WIFI動作", Toast.LENGTH_LONG).show();
}

public static boolean isWifi(Context mContext) {  
    ConnectivityManager connectivityManager = (ConnectivityManager) mContext  
            .getSystemService(Context.CONNECTIVITY_SERVICE);  
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();  
    if (activeNetInfo != null  
            && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {  
        return true;  
    }  
    return false;  
}  

}

最佳回答:


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class netReceiver extends BroadcastReceiver {
    Intent wifi = new Intent();

    @SuppressWarnings("static-access")
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = manager.getActiveNetworkInfo();
        if (activeNetInfo != null  
                && activeNetInfo.getType() == manager.TYPE_WIFI) {  
            wifi = new Intent(context, MyService.class);
            wifi.setAction(MainActivity.ACCESSIBILITY_SERVICE);
            context.startService(wifi);
        }else{
            wifi.setAction("net.s5c.Changelink.wifiOff");
            context.sendBroadcast(wifi);
        }

    }
}

我又重寫了一下,發現廣播接收者多次接到廣播還是不能啟動起來服務,我知道我寫的有問題,但那裡有問題應該怎麼寫啊??

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved