如何在mainActivity和小部件Activity之间传递数据?

时间:2020-07-02 16:02:38

标签: java android telephonymanager

所以我的应用程序正在打印imei号码和电话号码。 我想做的就是获取应用程序上已有的imei编号并将其打印在小部件上。

我应该做些什么吗?

我的主要活动是:

public class MainActivity extends AppCompatActivity {

    String phoneInfo() {
        final TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);


        StringBuilder sb = new StringBuilder();
        sb.append("tm.getDeviceId(): " + tm.getDeviceId() + "\n");
        sb.append("tm.getLine1Number(): " + tm.getLine1Number() + "\n");
        

        return sb.toString();
    }

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


        final TextView tv = (TextView) findViewById(R.id.info);
        tv.setText(phoneInfo());



            }

and my the widgetActivity is :

公共类NewAppWidget扩展了AppWidgetProvider {

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {

    CharSequence widgetText = NewAppWidgetConfigureActivity.loadTitlePref(context, appWidgetId);
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
    views.setTextViewText(R.id.appwidget_text, widgetText);


    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
    }
}

@Override
public void onDeleted(Context context, int[] appWidgetIds) {
    // When the user deletes the widget, delete the preference associated with it.
    for (int appWidgetId : appWidgetIds) {
        NewAppWidgetConfigureActivity.deleteTitlePref(context, appWidgetId);
    }
}

@Override
public void onEnabled(Context context) {
    // Enter relevant functionality for when the first widget is created
}

@Override
public void onDisabled(Context context) {
    // Enter relevant functionality for when the last widget is disabled
}

}

0 个答案:

没有答案