Java 正在尝试处理服务中的不同场景
我遇到了一个问题,我没有办法解决它 目标是,当用户单击按钮时,将根据在“设置”中选择的内容加载URL 问题是,我无法以正确的方式设置它 在逻辑上(对我来说),我尝试在服务中设置它。点击按钮>服务启动>URL从“IF-ELSE”加载。 问题是,我在“IF ELSE”-“方法长度必须从UI线程调用时出错,当前推断的线程是workerJava 正在尝试处理服务中的不同场景,java,android,multithreading,service,Java,Android,Multithreading,Service,我遇到了一个问题,我没有办法解决它 目标是,当用户单击按钮时,将根据在“设置”中选择的内容加载URL 问题是,我无法以正确的方式设置它 在逻辑上(对我来说),我尝试在服务中设置它。点击按钮>服务启动>URL从“IF-ELSE”加载。 问题是,我在“IF ELSE”-“方法长度必须从UI线程调用时出错,当前推断的线程是worker public static class Service extends IntentService { public Service() { s
public static class Service extends IntentService {
public Service() {
super("wallpaperchanger-download");
}
@Override
protected void onHandleIntent(Intent intent) {
MainActivity mainActivity;
mainActivity = new MainActivity();
if (mainActivity.mEditTextHashtag.length() > 2) {
WallpaperManager wm = WallpaperManager.getInstance(this);
int height = wm.getDesiredMinimumHeight();
int width = wm.getDesiredMinimumWidth();
String url = "https://source.unsplash.com/all/?" + mainActivity.mEditTextHashtag.getText() + "/" + width + "x" + height + "/";
try {
InputStream input = new URL(url).openStream();
Log.v(TAG, url);
wm.setStream(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
loading = false;
}
}
}
好吧,很公平。
我在UI线程中创建了新方法getPhoto();并将代码放入其中。然后,我在服务中调用mainActivity.getPhoto()。
问题是,我得到了一个错误-“尝试在空对象引用上调用虚拟方法'int-android.widget.EditText.length()
我该怎么做有什么想法吗
完整的代码及其荣耀:
package com.edip.splashwallpaper;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.io.InputStream;
import java.net.URL;
public class MainActivity extends android.app.Activity {
final static String TAG = "AllInOne";
final static int CHANGE_INTERVAL = 30 * 1000; //30 sec for testing
static boolean loading = false;
WallpaperManager wm;
//Layout Views
Switch mSwitchFixedPhoto, mSwitchControls, mSwitchSave, mSwitchPause;
Spinner mSpinnerCategories, mSpinnerInterval;
EditText mEditTextHashtag;
Button mWallpaperButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Layout Views Initialized
mSwitchFixedPhoto = (Switch) findViewById(R.id.sw_fixedphoto);
mSwitchControls = (Switch) findViewById(R.id.switch_controls);
mSwitchSave = (Switch) findViewById(R.id.switch_save);
mSwitchPause = (Switch) findViewById(R.id.switch_pause);
mSpinnerCategories = (Spinner) findViewById(R.id.spinner_categories);
mSpinnerInterval = (Spinner) findViewById(R.id.spinner_interval);
mEditTextHashtag = (EditText) findViewById(R.id.et_hashtag);
mWallpaperButton = (Button) findViewById(R.id.btn_set_wallpaper);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterCategory = ArrayAdapter.createFromResource(this,
R.array.categories_array, R.layout.dialog_spinner_layout);
// Specify the layout to use when the list of choices appears
adapterCategory.setDropDownViewResource(R.layout.dialog_spinner_layout);
// Apply the adapter to the spinner
mSpinnerCategories.setAdapter(adapterCategory);
ArrayAdapter<CharSequence> adapterInterval = ArrayAdapter.createFromResource(this,
R.array.interval_array, R.layout.dialog_spinner_layout);
adapterInterval.setDropDownViewResource(R.layout.dialog_spinner_layout);
mSpinnerInterval.setAdapter(adapterInterval);
mWallpaperButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PendingIntent pending = PendingIntent.getBroadcast(MainActivity.this,
666, new Intent("com.edip.splashwallpaper.CHANGE_WALLPAPTER_TIMER"),
PendingIntent.FLAG_CANCEL_CURRENT);
((AlarmManager) getSystemService(Context.ALARM_SERVICE))
.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
CHANGE_INTERVAL, pending);
}
});
}
public void getPhoto() {
if (mEditTextHashtag.length() > 2) {
wm = WallpaperManager.getInstance(this);
int height = wm.getDesiredMinimumHeight();
int width = wm.getDesiredMinimumWidth();
String url = "https://source.unsplash.com/all/?" + mEditTextHashtag.getText() + "/" + width + "x" + height + "/";
try {
InputStream input = new URL(url).openStream();
Log.v(TAG, url);
wm.setStream(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
loading = false;
} else {
Toast.makeText(this, "Something else", Toast.LENGTH_SHORT).show();
}
}
public static class Service extends IntentService {
public Service() {
super("wallpaperchanger-download");
}
@Override
protected void onHandleIntent(Intent intent) {
MainActivity mainActivity;
mainActivity = new MainActivity();
mainActivity.getPhoto();
}
}
public static class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
if (!loading) {
loading = true;
context.startService(new Intent(context, Service.class));
}
}
}
}
package com.edip.splash壁纸;
导入android.app.AlarmManager;
导入android.app.IntentService;
导入android.app.pendingent;
导入android.app.wallperManager;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.Spinner;
导入android.widget.Switch;
导入android.widget.Toast;
导入java.io.InputStream;
导入java.net.URL;
公共类MainActivity扩展了android.app.Activity{
最终静态字符串标记=“AllInOne”;
最终静态整数变化\u间隔=30*1000;//30秒用于测试
静态布尔加载=false;
壁纸经理;
//布局视图
切换mSwitchFixedPhoto、mSwitchControls、mSwitchSave、mSwitchPause;
微调器mSpinnerCategories,mSpinnerInterval;
EditText mEditTextHashtag;
按钮mWallpaperButton;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//布局视图已初始化
mSwitchFixedPhoto=(开关)findViewById(R.id.sw_fixedphoto);
mSwitchControls=(开关)findviewbyd(R.id.Switch\u控制);
mSwitchSave=(开关)findviewbyd(R.id.Switch\u save);
mSwitchPause=(开关)findviewbyd(R.id.Switch\u pause);
mSpinnerCategories=(微调器)findViewById(R.id.Spinner\u类别);
mSpinnerInterval=(微调器)findViewById(R.id.Spinner\u区间);
mEditTextHashtag=(EditText)findViewById(R.id.et_hashtag);
mWallpaperButton=(按钮)findViewById(R.id.btn\u set\u壁纸);
//使用字符串数组和默认微调器布局创建ArrayAdapter
ArrayAdapter adapterCategory=ArrayAdapter.createFromResource(此,
R.array.categories\u数组、R.layout.dialog\u微调器\u布局);
//指定显示选项列表时要使用的布局
adapterCategory.setDropDownViewResource(R.layout.dialog\u微调器\u布局);
//将适配器应用于微调器
mSpinnerCategories.setAdapter(AdapterCategories);
ArrayAdapterAdapterInterval=ArrayAdapter.createFromResource(此,
R.array.interval\u数组、R.layout.dialog\u微调器\u布局);
adapterInterval.setDropDownViewResource(R.layout.dialog\u微调器\u布局);
mspinneInterval.setAdapter(adapterInterval);
mWallpaperButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
PendingEvent pending=PendingEvent.getBroadcast(MainActivity.this,
666,新意图(“com.edip.splashwallpaper.CHANGE\u WALLPAPTER\u TIMER”),
挂起内容标志(取消当前);
((AlarmManager)getSystemService(Context.ALARM_服务))
.setRepeating(AlarmManager.RTC,System.currentTimeMillis(),
更改时间间隔(待定);
}
});
}
公众照片{
if(mEditTextHashtag.length()>2){
wm=wallperManager.getInstance(此);
int height=wm.getDesiredMinimumHeight();
int width=wm.getDesiredMinimumWidth();
字符串url=”https://source.unsplash.com/all/?“+mEditTextHashtag.getText()+”/“+width+“x”+height+”/”;
试一试{
InputStream输入=新URL(URL).openStream();
Log.v(标签、url);
设置流(输入);
input.close();
}捕获(例外e){
e、 printStackTrace();
}
加载=假;
}否则{
Toast.makeText(这是“其他东西”,Toast.LENGTH_SHORT).show();
}
}
公共静态类服务扩展了IntentService{
公共服务(){
超级(“壁纸变换器下载”);
}
@凌驾
受保护的手部内容无效(意图){
主要活动主要活动;
mainActivity=新的mainActivity();
mainActivity.getPhoto();
}
}
公共静态类AlarmReceiver扩展了BroadcastReceiver{
@凌驾
公共void onReceive(最终上下文、意图){
如果(!加载){
加载=真;
startService(新意图(context,Service.class));
}
}
}
}
谢谢:)首先,你应该不要自己实例化一项活动 其次,作为最佳实践,您的服务不应该知道您的活动,或者它有一个编辑文本。相反,您应该在创建PendingEvent时发送URL以加载到您的意图中,如下所示:
Intent intent = new Intent("com.edip.splashwallpaper.CHANGE_WALLPAPTER_TIMER");
intent.putExtra("USER_URL", "https://source.unsplash.com/all/?" + mEditTextHashtag.getText() + "/" + width + "x" + height + "/");
PendingIntent pending = PendingIntent.getBroadcast(MainActivity.this,
666, intent, PendingIntent.FLAG_CANCEL_CURRENT);
然后在您的服务中,像这样阅读url:
@Override
protected void onHandleIntent(Intent intent) {
String url = intent.getStringExtra("USER_URL");
// ...
}
谢谢你的信息,我会的