2011-10-14 50 views
0

我試圖在Android中做一個簡單的廣播來檢測屏幕上。對我來說,瞭解Android廣播功能是一種學習的過程。請幫忙。 我有Android的XML屏幕打開時在Android廣播上顯示Toast。

<application android:icon="@drawable/icon" android:label="@string/app_name"> 
     <activity android:name=".UsbddActivity" 
        android:label="@string/app_name"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 

     </activity> 


    <receiver android:name=".BootReceiver"> 
    <intent-filter> 
      <action android:name="android.intent.action.SCREEN_ON"></action> 


    </intent-filter> 
</receiver> 
    </application> 

主要的Java文件應該顯示敬酒

package usb.usbd; 
import android.app.Activity; 
import android.os.Bundle; 
public class UsbddActivity extends Activity { 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     } 
    } 

廣播類。

package usb.usbd; 

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.widget.Toast; 

public class BootReceiver extends BroadcastReceiver{ 

    @Override 
    public void onReceive(Context arg0, Intent arg1) { 

     Toast.makeText(arg0, "worked", Toast.LENGTH_LONG).show(); 
     run(arg0); 

    } 
    public void run(Context arg0) { 
      Toast.makeText(arg0, "sss", Toast.LENGTH_SHORT).show(); 
     } 


} 

它沒有顯示任何錯誤,也沒有顯示敬酒。我怎樣才能讓烤麪包在屏幕打開時顯示。

+1

如果我的答案下面幫助你找到原因,這不起作用,如果你標記它解決了,我將不勝感激。 – Force

回答

1

在這個網站看一看:http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

首先,與其他廣泛的鑄造意圖,爲Intent.ACTION_SCREEN_OFF和Intent.ACTION_SCREEN_ON你不能宣佈他們在你的Android清單!

您可以通過獲取ReceiveBootComplete權限來處理此操作,然後使用註冊Intent過濾器的onBootReceiver啓動服務。聽起來很複雜,但在這個網站上也有一個很好的例子。

/編輯:啊,我剛剛在例子中看到它是由onResume和onPause完成的。這可能是一種方式,但我不會推薦它。看到這個問題:Service and a BroadCastReceiver 這裏解釋瞭如何在您的服務中註冊Receiver。 此鏈接涵蓋了如何啓動服務啓動:http://www.androidcompetencycenter.com/2009/06/start-service-at-boot/

相關問題