我想同时使用广播和服务 activity

I want to use broadcast and services on the same activity

我的服务启动浏览器,当我停止此服务时,我的 UI 有一个文本视图,它会更新一些消息以显示已收到广播,但我无法这样做!

我的 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>

我在清单中发现了一个问题。您不能将 activity 声明为广播接收器。

<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,因为它与主要 activity 具有相同的布局。相反,您可以使用 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));
    }
} 

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

此外,服务中需要进行一些更改 class。

@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 class。