我想在同一活动中使用广播和服务

时间:2015-07-29 09:15:47

标签: java android android-intent service broadcastreceiver

我的服务启动浏览器,当我停止此服务时,我的UI有一个textview,它会更新一些消息,以显示广播被重新接收,但我无法这样做!

我的MainActivity.java文件: -

    public class MainActivity extends Activity
    {
private BroadcastReceiver receiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

protected void onDestroy(){
    super.onDestroy();
    unregisterReceiver(receiver);
}


public void startService(View view){
    startService(new Intent(getBaseContext(),MyService.class));
}

public void stopService(View view){
    stopService(new Intent(getBaseContext(),MyService.class));
}
}

我的广播接收文件是MyReceiver.java

 public class MyReceiver extends Activity {

private TextView txtvw;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        BroadcastReceiver receiver = new BroadcastReceiver(){ 
        @Override
            public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "Value ", Toast.LENGTH_LONG).show();     
            }
        };

    IntentFilter filter = new IntentFilter();
    filter.addAction("BROWSER_STOPPED");
    registerReceiver(receiver, filter);

    txtvw = (TextView)findViewById(R.id.textView2); 
    txtvw.setText("Done");

}

protected void onResume(){

    super.onResume();
}

}

这是我的服务文件MyService.java

    public class MyService extends Service{

@Override
public IBinder onBind(Intent arg1){
    return null;
}

@Override
public int onStartCommand(Intent intent,int flags, int startId){
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    showBrowser();
    return START_STICKY;
}

@Override
public void onDestroy(){
    super .onDestroy();
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
    // For sending Broadcast
            Intent intent = new Intent(this,MyReceiver.class);
            intent.setAction("BROWSER_STOPPED");
            sendBroadcast(intent);

}

protected void showBrowser(){

    String url = "http://www.google.com";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.setData(Uri.parse(url));
    this.startActivity(i);
}
}

我的布局文件:

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="@string/hello_world" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="57dp"
    android:onClick="startService"
    android:text="Start Browser" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1"
    android:layout_marginTop="53dp"
    android:onClick="stopService"
    android:text="Stop Browser" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/button2"
    android:layout_marginTop="93dp"
    android:text="TextView" />

我的清单文件:

 <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
    android:name=".MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<service android:name=".MyService"/>

<receiver android:name=".MyReceiver" >
    <intent-filter>
        <action android:name="BROWSER_STOPPED" />
    </intent-filter>
</receiver>

1 个答案:

答案 0 :(得分:1)

我在清单中找到了一个问题。您不能将活动声明为广播接收器。

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".MyService"/>

    <!--<receiver android:name=".MyReceiver" >-->
        <!--<intent-filter>-->
            <!--<action android:name="BROWSER_STOPPED" />-->
        <!--</intent-filter>-->
    <!--</receiver>-->
</application>

修改 我认为MyReceiver不是必需的,因为它与主要活动具有相同的布局。相反,您可以使用MainActivity作为广播接收器。

public class MainActivity extends Activity
{
    private static final String TAG = "MainActivity";
    private TextView txtvw;
    private BroadcastReceiver receiver;
    private IntentFilter filter;

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        filter = new IntentFilter();
        filter.addAction("BROWSER_STOPPED");

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(TAG, "onReceive");
                Toast.makeText(getApplicationContext(), "Value ", Toast.LENGTH_LONG).show();

                txtvw = (TextView) findViewById(R.id.textView2);
                txtvw.setText("Done");

            }
        };
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "unregistered");
        unregisterReceiver(receiver);
    }

    protected void onDestroy(){
        super.onDestroy();
    }


    public void startService(View view) {
        startService(new Intent(this, MyService.class));
    }

    public void stopService(View view){
        stopService(new Intent(this,MyService.class));
    }
} 

请注意,接收者在onPause()中注册,在onResume()中注销。只有当Activity位于前台时,才希望它处于活动状态。现在,如果您在onCreate()中注册接收器并在onDestroy()中取消注册,则当您的服务显示浏览器时,接收器将在onDestroy()方法中取消注册。现在,当你停止服务时,接收者不再听广播。

此外,Service类中还需要进行一些更改。

@Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
        // For sending Broadcast
        Intent intent = new Intent();
        intent.setAction("BROWSER_STOPPED");
        sendBroadcast(intent);
    }

意图不针对MyReceiver类。