我的onReceive方法被调用多次并从我的MainActivity(Wear)触发onCreate

时间:2018-01-14 22:34:36

标签: java android broadcastreceiver wear-os

我对android很新。我正在尝试使用WearableListenerService将数据从平板电脑发送到手机。这部分很好用,我可以通过日志查看数据的发送情况。问题是我在Listener类中从平板电脑接收数据,我必须将其传输到Mainactivity以更新我的视图。为此,我使用LocalBroadcaster,并在MainActivity中实现了onReceive方法。因此,当我给出从电话发送数据的命令时,onReceive会在大多数时间被多次调用2到3次,并且由于onCreate被此方法触发,因此重新创建了活动(我不知道这种行为是期待)。

以下是代码:

DataLayerListenerService.java (听众)

public class DataLayerListenerService extends WearableListenerService {

// Tag for Logcat
private static final String TAG = "DataLayerService";
private int notificationId = 001;
private String notif;

// Member for the Wear API handle
GoogleApiClient mGoogleApiClient;

@Override
public void onCreate() {
    super.onCreate();

    // Start the Wear API connection
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();
    mGoogleApiClient.connect();
}

//@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    Log.v(TAG, "onDataChanged: " + dataEvents);
    for (DataEvent event : dataEvents) {
        if (event.getType() == DataEvent.TYPE_CHANGED) {

            Log.e(TAG, "DataItem Changed: " + event.getDataItem().toString() + "\n"
                    + DataMapItem.fromDataItem(event.getDataItem()).getDataMap());

            String path = event.getDataItem().getUri().getPath();

            switch (path) {
                case DataLayerCommons.NOTIFICATION_PATH:
                    Log.v(TAG, "Data Changed for NOTIF_PATH: " + event.getDataItem().toString());
                    DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
                    notif = dataMapItem.getDataMap().getString(DataLayerCommons.NOTIFICATION_KEY);
                    Intent intent = new Intent(NOTIFICATION_RECEIVED);
                    intent.putExtra(NOTIFICATION_RECEIVED, notif);
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

                    break;
                case DataLayerCommons.COUNT_PATH:
                    Log.v(TAG, "Data Changed for COUNT_PATH: " + event.getDataItem() + "\n"
                            + "Count data = " + DataMapItem.fromDataItem(event.getDataItem())
                            .getDataMap().getInt(DataLayerCommons.COUNT_KEY));
                    break;
                default:
                    Log.v(TAG, "Data Changed for unrecognized path: " + path);
                    break;
            }
        } else if (event.getType() == DataEvent.TYPE_DELETED) {
            Log.v(TAG, "DataItem Deleted: " + event.getDataItem().toString());
        }

        }
    }
}

主要活动

public class MainActivity extends Activity {

private static final String TAG = "MainActivity";
public static final String NOTIFICATION_RECEIVED = "NOTIFICATION_RECEIVED";
private String notif="";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.e(TAG,"OnCreate");
    setContentView(R.layout.main_activity);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
            new IntentFilter(NOTIFICATION_RECEIVED));

}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        Log.e(TAG, "Got message!");
        notif = intent.getStringExtra(NOTIFICATION_RECEIVED);
        TextView warnView = findViewById(R.id.warningView);
        warnView.setText(notif);

    }
};

}

的AndroidManifest.xml

<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.VIBRATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat">


    <meta-data
        android:name="com.google.android.wearable.standalone"
        android:value="false" />

    <meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

    <service android:name=".DataLayerListenerService">
        <intent-filter>
            <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />

            <data
                android:host="*"
                android:pathPrefix="/notification"
                android:scheme="wear" />
        </intent-filter>
        <intent-filter>
            <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
            <data
                android:host="*"
                android:pathPrefix="/start-activity"
                android:scheme="wear" />
        </intent-filter>
    </service>

    <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>
        <intent-filter>
            <action android:name="com.example.android.wearable.datalayer.EXAMPLE" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

</application>

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我建议使用BroadcastReceiver类存储您的活动,而不是Application注册。

我的意思是:

class MyApp extends Application { public static MyActivity activity; } 类中的

创建一个存储您的活动的变量:

onCreate

将保存链接到onDestroy的此变量当前活动,并在public MyActivity extends Activity { void onCreate() { MyApp.activity = this; } void onDestroy() { MyApp.activity = null; } void redraw() { //redraw } } 时释放。

不知何故:

class MyService extends WearableListenerService {

void onDataChanged() {
if (MyApp.activity != null) {
MyApp.activity.redraw()
}
}

}

服务内部执行以下操作:

<application
    android:name=".MyApp"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat">

不要忘记在清单中设置应用程序:

LoadLibrary